-3

I have following json.

[{
    "id": 2,
    "date": {
        "1": "20-01-2012",
        "2": "21-01-2012",
        "3": "22-01-2012",
        "4": "23-01-2012",
    },
    "type":"Open",
    "url":"http://placehold.it/40x60/0bf/fff&text=A"
}
]

I was trying to do the dropdown using a foreach only date with the above json. It's should be like this at view.

<select id="cars">
  <option value="1">20-01-2012</option>
  <option value="2">21-01-2012</option>
  <option value="3">22-01-2012</option>
  <option value="4">23-01-2012</option>
</select>

Any idea? Thanks

Eric Dean
  • 1
  • 1
  • 4
    Do a `json_decode()` and loop and echo out the `date` key.. But more importantly you need to try something – Rotimi Mar 15 '20 at 17:37

1 Answers1

2

So I noticed a problem with you json. There is a trailing comma after the 4th date. But once you remove that, this code shall work

<?php
$json = '[{
    "id": 2,
    "date": {
        "1": "20-01-2012",
        "2": "21-01-2012",
        "3": "22-01-2012",
        "4": "23-01-2012"
    },
    "type":"Open",
    "url":"http://placehold.it/40x60/0bf/fff&text=A"
}]';

$json = json_decode($json,true);

?>

<select id="cars">
    <?php

       foreach ($json[0]['date'] as $k => $v) {

          echo '<option value="'.$k.'">'.$v.'</option>';
       }
    ?>

</select>

Try running it here

Riz-waan
  • 603
  • 3
  • 13