Search code examples
phpjsonredbean

convert numerically indexed associative-array in PHP, to valid JavaScript Object via JSON


Let's say you have a numerically indexed array that looks like this (obtained via RedBeanPHP's find operation):

[
[33=>["name"=>"John", "age"=25]], 
[55=>["name"="Jane", "age"=23]]
]

where 33 and 55 are id's of each of the 2 "beans" (basically associative-arrays).

And you want to convert the array to JSON so you can send it to a JavaScript client and use the data there as a JavaScript Object.

But you can't simply JSON_encode this because you'll end up with numerical keys in a JavaScript Object, and JavaScript doesn't like that.

What strategy can you use to convert this array to a JavaScript Object via JSON so that all the data (including id of each bean) is available at the JavaScript end? (To the RedBeanPHP folks out there: I'm hoping there's a native RedBeanPHP way to do this that I haven't found yet.)


Solution

  • Simple. You should try this. First iterate through the outer array and inside that get the key i.e id of the data. Add id to other values and push that array into resultant one.

    $result = array();
    $arr = [[33=>["name"=>"John", "age"=>25]],[55=>["name"=>"Jane", "age"=>23]]];
    foreach ($arr as $ar) {
        foreach ($ar as $key => $value) {
            $value['id'] = $key;
            array_push($result, $value);
        }
    }
    echo json_encode($result);
    

    Output :-

    [{"name":"John","age":25,"id":33},{"name":"Jane","age":23,"id":55}]