使用array_push将数组推入数组

时间:2015-04-27 10:09:08

标签: php arrays

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

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

首先,我希望ID成为数组的主键。在ID密钥中,我希望存储descriptionimage_medimage_full

我已经开始初始化一个数组并推送ID:

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

结果是:

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

现在我希望将三个元素推入此ID数组中。我想创建如下内容:

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]

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

description$image_desc是变量)

medium$image_med是变量)

full$image_full是变量)

我该怎么做?

3 个答案:

答案 0 :(得分:1)

让$ id为图片的ID:

$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的性能稍差,因为函数调用的开销(无论如何这是一个高级主题)

答案 1 :(得分:0)

是你在寻找什么?

$images = array(); // an array of all images
$image_id = $image['id'];

$images[$image_id] = array(
    'ID' => $image_id, // optional, would be repeating id you already have
    'description' => "Blabla",
    'medium' => "Blabla",
    'full' => "Blabla",
);

你会在我认为的循环中自动执行此操作...如果您不需要ID作为"键",那么:

$images = array();
$image1 = array(
        'ID' => $image_id,
        'description' => "Blabla",
        'medium' => "Blabla",
        'full' => "Blabla",
    );

array_push($images, $image1);

不确定您希望实现的目标。

答案 2 :(得分:0)

你的问题不是很清楚。你可能需要的东西可能是这样的:

// Create a list (of images)
$listImages = array();


// Information about an image (it can be constructed as displayed here,
// retrieved from a database or from other source)
$image = array(
    'id' => 123,
    'description' => 'Nice kitty',
    'medium' => 'http://www.blah.com/12345',
    'full' => 'http://www.blah.com/67890',
);

// Extract the ID of the image into a variable (this is for code clarity)
$imageId = $image['id'];

// Store the image in the list, indexed by image ID
$listImages[$imageId] = $image;


// Get/create another image...
$image = array(
    'id' => 456,
    'description' => 'another kitty',
    // ... other fields here
);

// ... put it into the list (skip the helper variable $imageId)
$listImages[$image['id']] = $image;

这就是print_r($listImages)的输出结果:

Array
(
    [123] => Array
        (
            [id] => 123
            [description] => Nice kitty
            [medium] => http://www.blah.com/12345
            [full] => http://www.blah.com/67890
        )

    [456] => Array
        (
            [id] => 456
            [description] => another kitty
        )

)