1

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.

1
  • instead of echo try to debug using print_r to see what is actually inside your array. Commented Aug 29, 2017 at 14:06

1 Answer 1

3

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.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.