简体   繁体   中英

How to iterate through array of dictionary in PHP

I have the following PHP code:

<?php
    exec("./mycode.py", $out)
    var_dump($out) 

?>

It produces the following output:

array(2) { [0]=> string(28) "{"ky2": "bar", "ky1": "foo"}" [1]=> string(30) "{"ky2": "bar2", "ky1": "foo2"}" }

How can I iterate the output above and print the result?

 Entry 0
    ky1 - foo
    ky2 - bar
 Entry 1
    ky1 - foo2
    ky2 - bar2

They Python code ( mycode.py ) is this:

#!/usr/bin/env python
import json
dict1 = {'ky1':'foo', 'ky2':'bar'}
dict2 = {'ky1':'foo2', 'ky2':'bar2'}
print json.dumps(dict1)
print json.dumps(dict2)

It prints this:

{"ky2": "bar", "ky1": "foo"}
{"ky2": "bar2", "ky1": "foo2"}

You just need aa foreach loop in conjunction with json_decode() on this one. While inside the loop, decode them each time. Consider this example:

$out = array(
    array('{"ky2": "bar", "ky1": "foo"}'),
    array('{"ky2": "bar2", "ky1": "foo2"}'),
);

$new_out = array();
foreach($out as $key => $value) {
    $values = json_decode($value[0], true); // <-- second parameter
    // set to TRUE to force return as an array
    ksort($values);
    $new_out['Entry '.$key] = $values;
}

echo '<pre>';
print_r($new_out);
echo '</pre>';

Sample Output:

Array
(
    [Entry 0] => Array
        (
            [ky1] => foo
            [ky2] => bar
        )

    [Entry 1] => Array
        (
            [ky1] => foo2
            [ky2] => bar2
        )

)

Edit: Or just maybe you just want an echo, I dont know.

foreach($out as $key => $value) {
    $values = json_decode($value[0], true);
    ksort($values);

    // or just plain echo
    echo "Entry $key <br/>";
    foreach($values as $index => $element) {
        echo str_repeat('&nbsp;', 5) . "$index - $element <br/>";
    }
}

Output:

Entry 0 
   ky1 - foo 
   ky2 - bar 
Entry 1 
   ky1 - foo2 
   ky2 - bar2 

Sample Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM