1

How can I convert the following JSON object array into an ordered list of values using PHP?

JSON Object

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

Desired Output

2098571,1315168,643316,210643,...
3
  • So far, I've only used: json_encode($object). It converts the object to a string but I'm still not sure how to isolate the values efficiently. Commented Nov 15, 2017 at 17:54
  • 1
    Why not string operations then ? Commented Nov 15, 2017 at 18:03
  • @SulthanAllaudeen Payden offered that solution and it worked. Great minds think alike! Commented Nov 15, 2017 at 18:07

2 Answers 2

2

You can cast the inner object to an array and implode that.

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

In general, casting objects to arrays and vice versa isn't always a good idea. But in this case if you don't care about the keys and just need the values, it should work consistently.

Sign up to request clarification or add additional context in comments.

Comments

1

From here: 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 ends up being what you need.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.