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]
5
  • 1
    What would be the desired JSON output ? It's quite unclear Commented Aug 12, 2014 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? Commented Aug 12, 2014 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 Commented Aug 12, 2014 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 Commented Aug 12, 2014 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. Commented Aug 12, 2014 at 13:09

2 Answers 2

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?

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

Comments

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++;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.