-3

In php, I'm trying to get the numbers (0, 13, 20, 45, 53, 56) from this json file:

{
    "0": {
        "classcat": "a",
    },
    "13": {
        "classcat": "b",
    },
    "20": {
        "classcat": "c",
    },
    "45": {
        "classcat": "d",
    },
    "53": {
        "classcat": "e",
    },
}

Im populating this file to a selectfield with a foreach loop. My desired output would be:

<select>
<option value="(classcatvalue)">(classcatvalue + number)</option>
<option value="a">a 0</option>
<option value="b">b 13</option>
<option value="c">c 20</option>
<option value="d">d 45</option>
<option value="e">e 53</option>
</select>

Looks simple, but i cannot figure it out. Any ideas?

stangerup
  • 19
  • 5
  • json_decode, loop the array\object. –  Dec 18 '17 at 21:19
  • http://php.net/manual/en/function.json-decode.php http://php.net/manual/en/control-structures.foreach.php – Sammitch Dec 18 '17 at 21:19
  • Why all the downvotes? Trying to make it simple, and with code examples, and still... – stangerup Dec 19 '17 at 09:20
  • @stangerup There is no PHP code in your question, which is the main subject itself. Anyway, you probably got the downvotes for not showing enough research since JSON parsing with PHP is a pretty common topic and a simple search for example could have solved this for you. And also, your JSON is invalid. Answers like the accepted one will only work if you make it valid... – sidyll Dec 19 '17 at 14:24

3 Answers3

0

One main problem is that your JSON is not valid. You have a lot of extra commas. After fixing that, you can transform it into an associative array with json_decode():

$options = json_decode(<<<JSON
{
    "0" : { "classcat": "a" },
    "13": { "classcat": "b" },
    "20": { "classcat": "c" },
    "45": { "classcat": "d" },
    "53": { "classcat": "e" }
}
JSON
, true);

And optionally simplify the values, removing the inner object/array and writing the values themselves:

array_walk($options, function(&$v, $k) { $v = $v['classcat']; });

Now it's just a matter of using a foreach loop to output your options:

<select>
  <option value="(classcatvalue)">(classcatvalue + number)</option>
<?php foreach ($options as $n => $cat) : ?>
  <option value="<?= $cat ?>"><?= "$cat $n" ?></option>
<?php endforeach; ?>
</select>

Hadn't the values been simplified, one ought to use $cat['classcat'] instead.

sidyll
  • 57,726
  • 14
  • 108
  • 151
0

Use json_decode() to convert the JSON to a PHP array, then use foreach to loop over it.

$array = json_decode($json, true);
foreach ($array as $number => $value) {
    $classcatvalue = $value['classcat'];
    echo "<option value="$classcatvalue">$number $classcatvalue</option>";
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
-2

Use array_keys after you json_decoded the string.

$values = array_keys(json_decode($json_str, true));

// Now you can output them like:
Echo $values[1]; // 13
Andreas
  • 23,610
  • 6
  • 30
  • 62