2

I have the following which assigns the values I need to an array in php

 $resultsAr[$row['stop_name']][$row['route_long_name']][] = $row['arrival_time'];

However when I convert this to JSON it does not have any keys.

echo json_encode($resultsAr);

e.g.

{
Stop1: {
Destination1: [
"11:13",
"11:25"
],
Destination2: [
"11:15",
"11:27"
],
Destination3: [
"11:14",
"11:23",
"11:26"
]
},

They keys are actually the values. How can I assign key names to the array?

Edited: the required JSON output would be keys with values:

[Stops => all stops] [destinations => destinations] [times => arrival times]
bleep-io
  • 25
  • 5
  • 1
    What would be the desired JSON output ? It's quite unclear – ClmentM Aug 12 '14 at 10:18
  • The `json_encode();` worked perfectly fine. The array structure specified, is being represented by the JSON you've sent us. What do you want your output to look like? – Zander Rootman Aug 12 '14 at 10:21
  • @ClémentMalet I've updated the question - I want to include keys with in the array - not use the stop/destination names as keys – bleep-io Aug 12 '14 at 10:24
  • @ZanderRootman yes it has encoded fine - just want to include key names so that when I decode it I can reference them – bleep-io Aug 12 '14 at 10:26
  • 1
    Try when you decode `json_decode($json, true);` Also, "Stop1", "Destination1" ect. are your Array "Keys". So your keys are there. – Zander Rootman Aug 12 '14 at 13:09

2 Answers2

1

Can you try:

$obj = new stdClass();

$obj->name = "Stop1";
$obj->data = array(
    array("Destination1",array("11:13","11:25")),
    array("Destination2",array("11:13","11:25")),
    array("Destination3",array("11:13","11:25")),
    );

echo json_encode($obj);

On a side note Only numeric items can appear without quotation. json.org

Also to explain stdclass - What is stdClass in PHP?

Community
  • 1
  • 1
Oliver Bayes-Shelton
  • 5,691
  • 10
  • 46
  • 84
0

You must be set key for array when you want to encode array to json

Example:

$i=0;
foreach ($rows as $row) {
       $resultsAr[$row['stop_name']][$row['route_long_name']][$i] = $row['arrival_time'];
       $i++;
}
prajmus
  • 2,995
  • 3
  • 31
  • 38
HamoonDBA
  • 158
  • 2
  • 8