1

my JSON currently looks like this

{   
"customers":
 [
    {
        "customer_id":3,
        "customer_name":"Rick",
        "Address":"333 North Road"
    },
    {
        "customer_id":4,
        "customer_name":"Robby",
        "Address":"444 North West Road"
    }
 ]
}

and I would like it to look like this

{
    "customers":
    [
        {
            "customer":
             {
                 "customer_id":3,
                 "customer_name":"Rick",
                 "Address":"333 North Road"
             }
        },
        {
            "customer":
            {
                  "customer_id":4,
                  "customer_name":"Robby",
                  "Address":"444 North West Road"
            }
        }
    ]
}

It is being created in this php script but I'm unsure how to add the customer attribute to each JSON object programmtically. help please?

//populate results
$json = array();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $array = array(
            'customer_id' => $row['CustomerID'],
            'customer_name' => $row['Name'],
            'Address' => $row['Address']
        );
    array_push($json, $array);
  foreach ($row as $r) {

  }
}

$jsonstring = '{"customers":'. json_encode($json). "}";
return $jsonstring;
3
  • 4
    $array = array("customer" =>array(...)); Commented Apr 18, 2016 at 22:49
  • but why do you want to change it, the first one is better Commented Apr 18, 2016 at 23:04
  • I'm trying to get the syntax to match a solution to another problem I am having to try and eliminate possibilities. Commented Apr 18, 2016 at 23:14

1 Answer 1

1
//populate results
$json = array();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $array = array("customer" => array(    // <-- change is here
               'customer_id' => $row['CustomerID'],
               'customer_name' => $row['Name'],
               'Address' => $row['Address']
            )
        );
    array_push($json, $array);
  foreach ($row as $r) {

  }
}

$jsonstring = '{"customers":'. json_encode($json). "}";
return $jsonstring;
Sign up to request clarification or add additional context in comments.

1 Comment

Had to wait for the timer to go up.

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.