Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert object of objects to array of objects (PHP, Laravel)

I am returning some data from DB using Eloquent and putting in in object of arrays. My response object to browser is displayed in this format:

// response()->json($response, 200);


[{
"id": 1,
"name": "car",
"make": ["bmw", "ford"]
"order": 1
},
{
"id": 2,
"name": "bike",
"make": ["aprilia"]
"order": 2
},
{
"id": 3,
"name": "boat",
"make": []
"order": 3
 },
(...)
]

Before returning it though, I wanted to filter it on server side. So I only return objects which do hold value in the "make" array.

So I am running this loop:

        foreach ($response as $key => $transport) {

            if (count($response[$key]['make']) == 0) {
                unset($response[$key]);
            };

        }

What php does is it converts the array to object and also adds keys to each inner object. So now my $response looks like:


// response()->json($response, 200);


{ // notice here it has changed from array to object
  "0": { // notice here it has added key "0"
    "id": 1,
    "name": "car",
    "make": ["bmw", "ford"]
    "order": 1
  },
    "1" : { // notice here it has added key "1"
    "id": 2,
    "name": "bike",
    "make": ["aprilia"]
    "order": 2
  },
 (...)
}

First of all - why? And second question - how to prevent/go back to array of objects response?

like image 404
Dom Avatar asked Apr 29 '19 14:04

Dom


People also ask

How to convert array of objects into array in PHP?

Converting an object to an array with typecasting technique: php class bag { public function __construct( $item1, $item2, $item3){ $this->item1 = $item1; $this->item2 =$item2; $this->item3 = $item3; } } $myBag = new bag("Books", "Ball", "Pens"); echo "Before conversion :".

How to turn object into array in PHP?

Type Casting object to an array it will convert a PHP object to an array. $foodArray = (array)$food; echo "After conversion :"; var_dump($foodArray);

How do you change an object to an array?

To convert an object to an array you use one of three methods: Object. keys() , Object. values() , and Object. entries() .

What is object in laravel?

A Laravel object is just a PHP object, but a PHP object that's been instantiated via the Application object's make method. You could also call the make method the make factory, or the make factory method.


1 Answers

When you unset a value from an indexed array in PHP, the existing indexes remain. Using a simple example with a small range of integers to illustrate, the following code unsets all odd integers from an array:

$numbers = range(1, 5); // [1, 2, 3, 4, 5];

foreach ($numbers as $index => $number) {
    if ($number % 2 !== 0) {
        unset($numbers[$index]);
    }
}

print_r($numbers);

Which yields:

Array
(
    [1] => 2
    [3] => 4
)

Note that the odd elements are removed, but the indexes of the existing elements are retained. Because of these gaps, the array isn't sequentially indexed at this point.

The consequence of this is, when you json_encode() this array, it assumes that these non-sequential indexes (let's just call them keys at this point) are to be retained, so it creates an object literal with keys instead. These keys are strings that just happen to be integers:

echo json_encode($numbers); // {"1":2,"3":4} 

Using array_values($numbers) will reset your array's indexes:

$reindexed = array_values($numbers);
echo json_encode($reindexed); // [2, 4]

Note: I mentioned in a comment that you can cast to an array using (array)—this is actually not correct as it will retain the non sequential indexes.

Hope this helps!

like image 133
Darragh Enright Avatar answered Sep 23 '22 02:09

Darragh Enright