3

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')
);
6
  • Can you post the exact values your going to convert into arrays? Commented Nov 7, 2016 at 4:28
  • Converting foreach to an array? You mean, converting objects to array. Commented Nov 7, 2016 at 4:29
  • 1
    If it's that you want to have arrays instead of objects you can use (array) $whatever and it will turn it to an array Commented Nov 7, 2016 at 4:31
  • @Xorifelse yeah probably, actually currently I'm testing Omnipay and it's need array for multiple items like ($output)->sendItems()->send(); Commented Nov 7, 2016 at 4:46
  • @Rasclatt I can use if it inside foreach, but I need use it outside foreach like my above comment Commented Nov 7, 2016 at 4:48

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.