2

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.

2 Answers 2

2

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.

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

Comments

0

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);

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.