Godhaze
Godhaze

Reputation: 155

How can I foreach loop through and print out specific values from multidimensional array

This maybe duplicate, but I couldn't find the anwser looking aroud topics.

I have an array, witch looks like this:

$itemx=
 [
     'Weapons'=>[
          'Sword'=> [
             'Name'   => 'Lurker',
             'Value'  => '12',
             'Made'   => 'Acient'
           ],

           'Shield'=> [
              'Name'   => 'Obi',
              'Value'  => '22',
              'Made'   => 'Acient'
            ],

            'Warhammer'=> [
               'Name'   => 'Clotch',
               'Value'  => '124',
               'Made'   => 'Acient'
             ]
     ],
     'Drinks'=>[
       'Water'=> [
          'Name'   => 'Clean-water',
          'Value'  => '1',
          'Made'   => 'Acient'
        ],

        'Wine'=> [
           'Name'   => 'Soff',
           'Value'  => '5',
           'Made'   => 'Acient'
         ],

         'Vodka'=> [
            'Name'   => 'Laudur',
            'Value'  => '7',
            'Made'   => 'Acient'
          ]
     ]


 ]; 

I want to echo out the item Categories(Weapons,Drinks),Types(Sword,Water,etc) what they hold.

I tried just an regular foreach and so they echo arrays.

  function getAllCategories()
  {
    foreach ($this->_prop as $cate)
    {
      echo $cate;
      foreach ($cate as $type)
      {
        echo $type;
      }

    }
  }

So i thought I can select from the arrays.

  function getAllCategories()
  {
    foreach ($this->_prop as $cate)
    {
      echo $cate[0];
      foreach ($cate as $type)
      {
        echo $type[0];
      }

    }
  }

But they echo'd nothing and I dont understand how could I print those values out that I want.

Upvotes: 1

Views: 639

Answers (1)

ishegg
ishegg

Reputation: 9937

You need to get both the index and the value (as an array) in each foreach(), so you can keep going in "through the dimensions":

function getAllCategories()
{
  foreach ($this->_prop as $cate => $items)
  {
    echo $cate."<br>";
    foreach ($items as $type => $values)
    {
      echo $type."<br>";
    }

    echo "<br>";
  }
}

/* result
Weapons
Sword
Shield
Warhammer

Drinks
Water
Wine
Vodka
*/

Now, in the first level, $cate is the index of each element, and $items is the array containing the next level.

Then $values is an array with the last tier of your array. If you add more levels, you can keep going at in the same way.

Upvotes: 3

Related Questions