Home > OS >  Create multidimensional array using a foreach and for loop
Create multidimensional array using a foreach and for loop

Time:11-05

[
{
    "Sports":
    {
        "Series": "Wordlcup"
    },
    "CricketTeams":
    {
        "India": "india.com",
        "Australia": "australia.com",
        "England": "england.com",
    }
},
{
    "Sports":
    {
        "Series": "Places"
    },
    "CricketTeams":
    {
        "Pune": "/pune",
        "Delhi": "/delhi",
        "Ranchi": "/ranchi/"
    }
},
{
    "Sports":
    {
        "Series": "man of the match"
    },
    "menuItems":
    {
        "Rohit": "rohit.com",
        "Kohli": "kohli.com"
    }
}]
for($i = 0; $i < count($json_data); $i  ) {
    echo "<br>";
    foreach($json_data[$keys[$i]] as $item => $name) {
        echo $name['Series'];
    }
}

The data is coming from Json file so i am using json-data here I am getting output as :

Worldcup
places
Man of the match

but i need the output as below :

Worldcup 
India
Australia
England

Places
Pune
Delhi
Ranchi

Man of the match
Rohit
Kohli

CodePudding user response:

Don't print the series in the inner loop, it should be printed in the outer loop. The inner loop iterates over the keys that contain the countries, and it contains a third loop to iterate over the array keys to print the country names.

$keys = ['CricketTeams', 'menuItems'];
foreach ($json_data as $item) {
    echo "{$item['Sports']['Series']}<br>";
    foreach ($keys as $key) {
        if (isset($item[$key])) {
            foreach (array_keys($item[$key]) as $country) {
                echo "$country<br>";
            }
        }
    }
    echo "<br>";
}

CodePudding user response:

Another possible solution:

foreach ($json_data as $rowId => $row) {

    echo ($rowId > 0 ? '<br>' : ''), ucfirst($row['Sports']['Series']), '<br>';
    
    foreach (end($row) as $key => $val) {
       echo $key, '<br>';
    }
}
  • Related