修改JSON数据

时间:2015-05-29 14:13:14

标签: php json

我想用PHP修改JSON数据格式。

我有一个这样的数组:

Array ( 
[0] => stdClass Object ( 
    [0] => Thu Apr 30 12:25:12 +0000 2015 ) 
[1] => stdClass Object ( 
     [0] => Wed Apr 15 21:57:05 +0000 2015 ) 
      )

我试过了json_encode($ data);但它是这样的:

[{"0":"Thu Apr 30 12:25:12 +0000 2015"},{"0":"Wed Apr 15 21:57:05 +0000   2015"}]

但我想要这种格式:

["Thu Apr 30 12:25:12 +0000 2015","Wed Apr 15 21:57:05 +0000   2015"]

我该怎么办?

3 个答案:

答案 0 :(得分:1)

在调用json_encode()之前,您需要更改数组的结构。

我不确定为什么你有这样一个结构的数组,你可能想看看如何以这种格式创建$data。但是,使用你拥有的东西:

$dates = array();
foreach ($data as $obj) {
    $dates[] = $obj->0;
}
print_r(json_encode($dates));

另外, anant kumar singh 提出了一个非常好的观点,如果您稍后反序列化此JSON,它将不会产生相同的数组。因此,您应该重新审视此数组是如何序列化和反序列化的,并确保它们匹配。

答案 1 :(得分:0)

尝试此函数,将数组作为参数传递

function to_array_of_strings($data){
    $result_array = array();
        foreach($data as $key => $object){
            foreach($object as $object_key => $object_value){
               $result_array[] = $object_value;
            }
        }
    return $result_array;
}

答案 2 :(得分:0)

我试过这个它有效:

 $i=0;
    foreach($fin as $key1 => $value){
        foreach($value as $key2 => $value2){
            $dates[$i]= $value2 ;
            $i++;
        }
    }