My array $array contains the following:
Array ( [0] => Array (
[label] => Location and Contact
[description] =>
) [1] => Array (
[label] => Province
[name] => province
[options] => Array ( [0] => Province 1
[1] => Province 2
[2] => Province 3 )
) [2] => Array (
[label] => City
[name] => city
[options] => Array ( [0] => City 1
[1] => City 2
[2] => City 3 )
)
What I want to achieve is to loop those three cities at the bottom, probably with the use of the [name] => city.
What I've tried so far (which isn't really looking good):
foreach ($array as $arr) {
foreach ($arr['options'] as $option) {
?>
» <?php echo $option; ?><br />
<?php
}
}
My obvious problem with the code is the foreach loop within foreach loop plus I haven't figured out how to identify [name] => city from [name] => province, both of them having [options].
I'm fairly new to looping arrays.
UPDATE (WITH MY ANSWER)
Combining worldofjr's answer and my modification so I can enclose each loop in a container like <li>, <option>, <div>
, etc, I just created two foreach's:
foreach($array as $arr) {
if($arr['name'] == "city") {
$cities = $arr['options'];
}
}
echo '<select>';
foreach($cities as $city){
echo '<option value="'.$city.'" class="class1 class2" data-att="att">'.$city.'</option>';
}
echo '</select>';
2 Answers 2
You could use implode($glue,$array)
as follows;
foreach($array as $arr) {
if($arr['name'] == "city") {
echo implode('<br>',$arr['options']);
}
}
or if you want to print a list of the cities, wrap the implode()
with list tags, like this;
foreach($array as $arr) {
if($arr['name'] == "city") {
echo "<ul><li>" . implode("</li><li>", $arr['options']) . "</li></ul>";
}
}
See PHP manual: implode.
Hope this helps!
-
Helped a lot. Need to study more about implodes and explodes. Thank you. :)hello– hello2014年09月17日 06:28:58 +00:00Commented Sep 17, 2014 at 6:28
I don't understand at all, but I what you want is simply output the three cities, yo can do this
foreach ($array as $arr)
{
if ($arry['name'] == 'city')
{
foreach ($arr['options'] as $option)
{
echo $option . '<br />';
}
}
}
That's enough?
array_filter
foreach
. Just wrap theimplode()
with list tags, ie;echo "<ul><li>" . implode("</li><li>", $arr['options']) . "</li></ul>";