PHP 数组到 json 没有索引

PHP array to json without indices

我是 PHP 的新手,我正在尝试将数组转换为 json,不带索引。

举个例子,我有:

[{"name":"Dean"},{"last_name":"Don"},{"age":31},{"height":181}]

我需要它是单个 json 对象:

{
"name":"Dean,
"last_name":"Don",
"age":31,
"height":181
}

我尝试使用 json_encode() 但我得到的都不正确,我尝试指定 JSON_FORCE_OBJECT,其中放置了我不想要的索引。

有人知道如何解决吗? 谢谢

你试过了吗 json_encode(array_values($array))?

您可以使用 json_decode 将 json 转换为数组。使用 array_reduce 创建一个新数组。使用json_encode再次将数组转换为json

$str = '[{"name":"Dean"},{"last_name":"Don"},{"age":31},{"height":181}]';

//Convert the json into array
$arr = json_decode($str, true);

//Make the multi dementional array into an associative array
$arr = array_reduce($arr, function($c, $v){
    foreach ($v as $key => $val) $c[$key] = $val;
    return $c;
}, array());

//Convert the array to json
$result = json_encode($arr);

echo $result;

这将导致:

{"name":"Dean","last_name":"Don","age":31,"height":181}

JSON 的第一位看起来像这样编码键值对数组的结果:

$data = [
    ['name' => 'Dean'],
    ['last_name' => 'Don'],
    ['age' => 31],
    ['height' => 181]
];

如果这就是您的起点,您可以迭代属性集并构建一个将编码为单个对象的实体。

foreach ($data as $attribute) {
    $entity[key($attribute)] = reset($attribute);
}

echo json_encode($entity);

如评论中所述,可能一种更好的方法可以在您的代码中更早地执行此操作,因此您可以首先创建您想要的实体而不是某些东西就像 $data 示例一样,您必须重新处理才能输出它。

另一种方法是解码、合并和重新编码:

$json = '[{"name":"Dean"},{"last_name":"Don"},{"age":31},{"height":181}]';
$data = json_decode($json,true); // decode
$data = array_merge(...$data); // merge
echo json_encode($data, JSON_PRETTY_PRINT); // recode

输出:

{
    "name": "Dean", 
    "last_name": "Don", 
    "age": 31, 
    "height": 181 
}