使用array_push将数组推入数组 [英] Push array into an array using array_push

查看:372
本文介绍了使用array_push将数组推入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有四个存储在变量中的数据元素。

I have four elements of data stored in variables.

我希望创建一个多维数组。

I wish to create a multi-dimensional array.

首先,我希望ID是该阵列的主键。在ID键中,我希望存储说明 image_med image_full

Firstly, I wish the ID to be the main key for the array. And within the ID key, I wish to store description, image_med and image_full

我首先初始化一个数组并推送ID:

I have started by initialising an array and pushing the ID:

$image_id = $image['id'];
$this_image = array();
array_push($this_image, $image_id);

结果是:

array(1) {
  [0]=>
  int(2161)
}

现在我想再介绍三个元素放入此ID数组。我想创建以下内容:

Now I wish to push three more elements into this ID array. I'd like to create something like the following:

array(1) {
      ['ID']=>
      int(2161)
      array(3){
       ['description'] => string(Description goes here),
       ['medium'] => string(http://www.blah.com/12345),
       ['full'] => string(http://www.blah.com/67890)
      }
    }

因此,首先将父键称为 ID 而不只是 [0]

So first of all the parent key is called ID not just [0]

其次,以下三个变量及其键被添加:

And secondly that the following three variables are added with their keys:

描述 $ image_desc 是变量)

medium $ image_med 是变量)

full $ image_full 是变量)

我该怎么做?

推荐答案

让$ id为图片的ID:

Let $id be the id of the image:

$array=array();

//then you can use this code in a loop:
$array[$id]=array(
'description'=>$image_desc,
'medium'=>$image_med,
'full'=> image_full
);

不需要使用array_push函数,由于函数调用的开销,array_push实际上具有较差的性能(无论如何,这是一个高级主题)

There is no need to use array_push function, actually array_push has a little worse performance because of function call's overhead (this is an advanced topic, anyway)

这篇关于使用array_push将数组推入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆