Suraj Roy Suraj Roy - 2 months ago 11
JSON Question

How to convert numerically indexed array to associative array

I have this

{"1":{"name":"cat"},"2":{"name":"elephant"}}


how to convert it to

[{"name":"dog"},{"name":"cat"}]


or convert it to vice versa

Answer
$arr = json_decode('{"1":{"name":"cat"},"2":{"name":"elephant"}}');
$result = array();
foreach($arr as $item) {
    $data = ['name' => $item->name];
    $result[] = $data;
}

$json = json_encode($result);
print_r($json);