skip to Main Content
[
{
    "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

2

Answers


  1. 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>";
    }
    
    Login or Signup to reply.
  2. 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>';
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search