简体   繁体   中英

How to add multidimensional array elements using a foreach loop

I'm having trouble with the looping of what I want to do.

I have an array called $data which at present holds only two elements:

array(2) {
  ["pagination"]=>
  string(166) "https://someURL.com"
  ["images"]=>
  string(3) "foo"
}

I now wish to add another dimension, within the [images] element. And again within that element, another two pieces of data. The result would look like this:

array(2) {
  ["pagination"]=>
  string(166) "https://someURL.com"
  ["images"]=> array(5) {
      [0]=> array(2){
        ["image_url"]=> string(1234) "http://www.blah.com"
        ["caption"]=> string(1234) "Here is my caption strng"
      }
      [1]=> array(2){
        ["image_url"]=> string(1234) "http://www.blah.com"
        ["caption"]=> string(1234) "Here is my caption strng"
      } 
      [2]=> array(2){
        ["image_url"]=> string(1234) "http://www.blah.com"
        ["caption"]=> string(1234) "Here is my caption strng"
      } 
      [3]=> array(2){
        ["image_url"]=> string(1234) "http://www.blah.com"
        ["caption"]=> string(1234) "Here is my caption strng"
      } 
      [4]=> array(2){
        ["image_url"]=> string(1234) "http://www.blah.com"
        ["caption"]=> string(1234) "Here is my caption strng"
      }  
}

My question is, how I can extract data from it's original source (an array called $pics ) and input it into my new [images] element in the manner above?

At present I am able to output the image_url and caption data using the following loop, I just can't figure out how to push that data into the array above.

foreach($pics['data'] as $pic){
    $caption = $pic['caption']['text'];
    $image = $pic['images']['standard_resolution']['url'];
}

Try something like this:

foreach($pics['data'] as $pics)
{
     $caption = $pic['caption']['text'];
     $image = $pic['images']['standard_resolution']['url'];
     $data['images'][] = array($image, $caption);
}

EDIT: $data['images'] must be set as an array before the foreach statement: $data['images'] = array();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM