Reputation: 33
Anyone can help me
I have a little problem with the following code
foreach ($products as $product) {
$product->name;
$product->code;
...
}
My output code with var_dump($products)
array
0 =>
object(stdClass)
...
...
...
1 =>
object(stdClass)
...
...
...
And I need output something like this
$output = array(
array('name' => 'item1', 'code' => 'code1', 'price' => '10.00'),
array('name' => 'item2', 'code' => 'code2', 'price' => '20.00')
);
Upvotes: 3
Views: 792
Reputation: 23978
For this purpose, there is a function is php json_decode()
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
Need to use this function sensibly.
As you see in the function description,
The function's three parameters:
1) Variable to be converted.
2) Return as associative array.
3) Depth: default => 512. Means upto depth of 512 levels (in case of multi-dimensional array or complex object), the child elements will be converted into arrays if second parameter is set to true
.
First encode your variable by json_encode() and the decode it with using json_decode().
json_decode() 's second parameter should be set to true
.
This true
means return associative array instead of original type.
Pseudo code:
$output = json_decode(json_encode($yourVar), TRUE);
Upvotes: 3