如何将数字索引数组转换为关联数组

时间:2016-09-21 10:23:39

标签: php arrays json

我有这个

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

如何将其转换为

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

或将其转换为反之亦然

1 个答案:

答案 0 :(得分:0)

$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);