Home > Back-end >  Rearrange each key as object into an object of keys
Rearrange each key as object into an object of keys

Time:03-13

So I can't exactly spot what I am doing wrong here, so I'm hoping the community could give me a boost so I can figure out exactly what is causing this.

I have the following foreach where I'm setting a bunch of objects into an array of objects.

$result = [];
foreach($items as $item) {
    $result[] = ['id' => $item->get_id()];
    $result[] = ['media_type' => $item->get_media_type()];
}
var_dump($result);

With the above code, I am getting the following output on var_dump($result);:

[
    {
        "id": "17992874035441353"
    },
    {
        "media_type": "CAROUSEL_ALBUM"
    },
    {
        "id": "17842233125750202"
    },
    {
        "media_type": "IMAGE"
    }
]

Here is what I am aiming for:

[
    {
        "id": "17992874035441353",
        "media_type": "CAROUSEL_ALBUM"
    },
    {
        "id": "17842233125750202",
        "media_type": "IMAGE"
    },
]

Could someone spot what might be going on with how I'm formatting the foreach and setting up the new array? I've tried multiple different things and can't seem to figure out the answer.

CodePudding user response:

Every time you do: $result[] = ..., you're pushing a new array element into the array. You need to push all the data as one single array:

foreach($items as $item) {
    $result[] = [
        'id' => $item->get_id(),
        'media_type' => $item->get_media_type(),
    ];
}
  •  Tags:  
  • php
  • Related