Geoff_S
Geoff_S

Reputation: 5107

adding object elements to array when they don't have keys=>values

I'm currently building an array off of an object and I've got one element called images that has multiple sub elements called 'urls' structured like so

categories": [
    {
      "images": [
        {

          "urls": [
            "path/test.jpg",
            "path/test2.jpg",
            "path/test3.jpg"
          ],
        },
        {

          "urls": [
            "path/test4.jpg",
            "path/test5.jpg",
            "path/test6.jpg"
          ],

        },
        {

          "urls": [
            "path/test7.jpg",
            "path/test8.jpg",
            "path/test9.jpg"
          ],

        },
]

The values there don't have keys, it's just the url path but I'd like to add these to my $groupItem array and just have each url be it's own element on the same level as the group number (basically I'm exporting and need each url as it's own column)

The structure I want

0 =>"path/test.jpg",
1 =>"path/test2.jpg",
2 =>"path/test3.jpg"
3 =>"path/test4.jpg",
4 =>"path/test5.jpg",
5 =>"path/test6.jpg"
6 =>"path/test7.jpg",
7 =>"path/test8.jpg",
8 =>"path/test9.jpg"

The loop/array:

foreach($prices->groups as $group){ 
    $groupItem = array(); 
    $groupItem["number"] = $group->number;

    foreach($group->images as $images){
        $groupItem["urls"] = $images->urls;
    }
}

How can I simply just add on any url to the groupItem level of that array?

Upvotes: 0

Views: 44

Answers (2)

The fourth bird
The fourth bird

Reputation: 163267

You might also use array_column with (from php 5.6) a variable length argument list:

For example, for the images which contains an array of objects where each object has a property urls and contains an array of image urls:

foreach ($prices->groups as $group) {
    $groupItem = array();
    $groupItem["number"] = $group->number;
    $groupItem= array_merge($groupItem, ...array_column($group->images, "urls"));    
}

Demo

Upvotes: 1

Alex Howansky
Alex Howansky

Reputation: 53543

Outside the outer loop, init the value to an empty array:

$groupItem["urls"] = [];

Then use the empty array reference operator to append new values to the end of an array:

foreach($group->images as $images){
    $groupItem["urls"][] = $images->urls; // add this url to the end of the list
}

Alternatively, use array_push():

foreach($group->images as $images){
    array_push($groupItem["urls"], $images->urls);
}

I think you can probably also skip the inner loop and just use the array explode operator like this:

array_push($groupItem["urls"], ...$images->urls);

Upvotes: 2

Related Questions