如何将简单的 php 数组转换为带头的 json 数据

How to convert simple php array into json data with heads

我正在 WordPress 中获取 post 对象数据,这是我的代码

$pre_items = get_post_meta( $post_object->ID, 'rudr_select2_tags');

print_r 给我提供了这个数据

Array ( [0] => Array ( [Apple iPhone 5,Apple iPhone 6] => 1 ) )

我写了下面的代码

  $pre_items = get_post_meta( $post_object->ID, 'rudr_select2_tags');
  $new_arr = array();

  foreach($pre_items as $arr){
    $process_array = array();
    $process_array['id'] = $arr;
    $process_array['name'] = $arr;
    array_push($new_arr,$process_array);
   }

   $items = json_encode($new_arr);  

但是这个代码returns数据

[{"id":{"Apple iPhone 5,Apple iPhone 6":1},"name":{"Apple iPhone 5,Apple iPhone 6":1}}]

但我想要以下格式的数据

[{id: Apple iPhone 5, name: "Apple iPhone 5"},
{id: Apple iPhone 6, name: "Apple iPhone 5"}
]

请帮助实现这个目标。

将第三个参数添加到 get_post_meta 以切换 return 单个值,并展开数组键以分隔设备以便按照您的示例构建数据。

$pre_items = get_post_meta( $post_object->ID, 'rudr_select2_tags', true);
$new_arr = array();

foreach($pre_items as $key => $value ){

    // Split key into array.
    $devices = explode( ',', $key );

    // name is set to first device.
    $name = $devices[0];

    foreach ( $devices as $device ) {
        $process_array = array(
            'id' => $device,
            'name' => $name,
        );
        array_push($new_arr, $process_array);
    }

}

$items = json_encode($new_arr);