【问题标题】:How to convert simple php array into json data with heads如何将简单的php数组转换为带头的json数据
【发布时间】:2021-08-12 06:39:14
【问题描述】:

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

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

但此代码返回数据

[{"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"}
]

请帮助如何实现这一点。

【问题讨论】:

    标签: php arrays json wordpress converters


    【解决方案1】:

    将第三个参数添加到 get_post_meta 以切换单个值的返回,并分解数组键以分隔设备以便根据您的示例构造数据。

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

    【讨论】:

    • 谢谢,可以了,只是第7行$key前少了一个逗号
    猜你喜欢
    • 1970-01-01
    • 2012-09-15
    • 2019-04-14
    • 2020-05-19
    • 2016-02-05
    • 2016-06-25
    • 2014-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多