-3

I have a array like this. I want to loop over the array, but do not know how to handle the internal arrays. Can anyone help me?

$a = array(
  0 => array(
    'B' => array(
      'company' => 'ZZZZZZ'
    ),
    'User' => array(
      'company' => 'ABC'
    ),
    0 => array(
      'jumlah' => null,
      'jumbuy' => '98990',
      'admin' => '2010'
    )
  )
);
Marshall Davis
  • 3,337
  • 5
  • 39
  • 47
faizal12
  • 1
  • 1

2 Answers2

0

If you want to use foreach on this array do like this.

foreach($a as $key=>$value)
{
    print_r($value);

}

You can also use nested foreach.

ajaykumartak
  • 776
  • 9
  • 29
  • What if he doesn't know how deep the array is? – Marshall Davis Apr 17 '15 at 04:49
  • That's the other condition, i already mentioned that "if you want to use foreach on this array then do like this" – ajaykumartak Apr 17 '15 at 04:54
  • And as she has no idea about array and foreach so for now it's best for her to start with it.. – ajaykumartak Apr 17 '15 at 04:56
  • If you nest the `foreach` N times, you go only go N deep. Also, you skip over or throw a warning for each non-array value. If you don't know the depth, you can't know how deep to nest. I feel like you should answer not only for the poster but for anyone who may come across this answer. The point of Stack Overflow is to build a knowledge repository so it's best to answer the question fully, for future readers. – Marshall Davis Apr 17 '15 at 05:04
  • Ok sorry, I will take care of it in future. – ajaykumartak Apr 17 '15 at 05:06
0

You can use a recursive function (but these can spiral out of control).

function print_array($array) {
  foreach($array as $key => $value) {
    echo "{$key} is: ";
    if (is_array($value)) {
      echo "an array.\n"
      print_array($value);
    } else {
      echo "{$value}.\n";
    }
    echo "\n";
  }
Marshall Davis
  • 3,337
  • 5
  • 39
  • 47