从PHP中的JSON对象创建值列表

时间:2017-11-15 17:46:41

标签: php json

如何使用PHP将以下JSON对象数组转换为有序的值列表?

JSON对象

array:1 [▼
  0 => {#226 ▼
    +"sum(hour0)": "2098571"
    +"sum(hour1)": "1316168"
    +"sum(hour2)": "643316"
    +"sum(hour3)": "210643"
    +"sum(hour4)": "97135"
    +"sum(hour5)": "25334"
    +"sum(hour6)": "20451"
    +"sum(hour7)": "20639"
    +"sum(hour8)": "20382"
    +"sum(hour9)": "16966"
    +"sum(hour10)": "25301"
    +"sum(hour11)": "17352"
    +"sum(hour12)": "23883"
    +"sum(hour13)": "425294"
    +"sum(hour14)": "3776592"
    +"sum(hour15)": "5292751"
    +"sum(hour16)": "5945308"
    +"sum(hour17)": "952250"
    +"sum(hour18)": "0"
    +"sum(hour19)": "0"
    +"sum(hour20)": "0"
    +"sum(hour21)": "0"
    +"sum(hour22)": "0"
    +"sum(hour23)": "0"
  }
]

期望输出

2098571,1315168,643316,210643,...

2 个答案:

答案 0 :(得分:2)

您可以将内部对象强制转换为数组并将其内爆。

$string = implode(',', (array) $object[0]);

通常,将对象转换为数组而反之亦然并不总是一个好主意。但在这种情况下,如果您不关心密钥并且只需要值,那么它应该始终如一地工作。

答案 1 :(得分:1)

从这里开始:How do I loop through JSON object

You can foreach through an Object in PHP.

<?php
    $objectJSON = JSON OBJECT;
    $string = '';
    foreach ($objectJSON[0] as $key => $value)
        {
            $values[] = $value;
        }
    $string = implode(",", $values);
?>

$string最终成为您所需要的。