Early73
Early73

Reputation: 503

php json multidimensional array syntax

I have a problem with the JSON I'm creating in PHP; I create the array in a while loop from an sql query. $featuresCSV is a comma-separated string like "1,3,4". In the JSON I need it to end up like feature-1: 1,feature-2: 1,feature-3: 1 The 1 represents true for my checkbox in my front-end program.

while ($stmt2->fetch()) {

  $features = array();
  $featuresTmp = explode(',', $featuresCSV, -1);

  foreach ($featuresTmp as &$featureItem) {
    $features[] = array("feature-" . $featureItem => 1);
  }

  $items[] = array('price' => $price, 'image' => $image, 'features' => $features);
}
...
json_encode($output);

The JSON ends up looking like this:

{"price":8900,
"image":"4d3f22fe-9f1a-4a7e-a564-993c821b2279.jpg",
"features":[{"feature-1":1},{"feature-2":1}]}

but I need it to look like this:

{"price":8900,
"image":"4d3f22fe-9f1a-4a7e-a564-993c821b2279.jpg",
"features":[{"feature-1":1,"feature-2":1}]}

Notice how feature-1 and feature-2 aren't separated by brackets in the second.

Upvotes: 2

Views: 85

Answers (2)

Josh S.
Josh S.

Reputation: 597

Here ya go

while ($stmt2->fetch()) {

$features = array();
$featuresTmp = explode(',', $featuresCSV, -1);


foreach ($featuresTmp as &$featureItem) {
$features["feature-$featureItem"] = 1;
}

$items[] = array('price' => $price, 'image' => $image, 'features' => $features);
}
...
json_encode($output);

Upvotes: 0

SQL Hacks
SQL Hacks

Reputation: 1332

You need to assign the elements at "feature-1" and "feature-2".

foreach ($featuresTmp as &$featureItem) {
   $features["feature-" . $featureItem] = 1;
}

The syntax $feature[] = ... is for appending to the end of an array.

Upvotes: 2

Related Questions