-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

1
  • 4
    Do a json_decode() and loop and echo out the date key.. But more importantly you need to try something Commented Mar 15, 2020 at 17:37

1 Answer 1

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.