Karem
Karem

Reputation: 18103

Output from this array

array(2) {
  [0]=>
  array(4) {
    ["id"]=>
    string(1) "1"
    ["name"]=>
    string(3) "Lim"
    ["subproject_id"]=>
    string(1) "5"
    ["subproject_name"]=>
    string(4) "Mads"
  }
  [1]=>
  array(1) {
    [0]=>
    array(4) {
      ["id"]=>
      string(1) "1"
      ["name"]=>
      string(3) "Lim"
      ["subproject_id"]=>
      string(1) "4"
      ["subproject_name"]=>
      string(5) "KANYE"
    }
  }
}

How can I output each name and subproject_name?

A simple foreach() will only get the first one.

Upvotes: 1

Views: 148

Answers (3)

Uladzimir Pasvistselik
Uladzimir Pasvistselik

Reputation: 3921

Try this:

array_walk_recursive($array, function($item, $key) {
    if (in_array($key, array('name', 'subproject_name'))) {
        echo $item;
    }
});

See http://php.net/manual/en/function.array-walk-recursive.php

Note: for PHP 5.3.0 you can use callback, in earlier versions you need non-anonymous function.

Upvotes: 1

Riz
Riz

Reputation: 10246

Don't know how much that array could vary, but here is one simple solution.

foreach($array as $key => $value){

    if(!isset($value['id']))
        $value = $value[0];


    echo $value['name'];
    echo $value['subproject_name'];
}

if its getting deeper, you can use 'while' instead of 'if'.

Upvotes: 1

arkascha
arkascha

Reputation: 42885

Consult the php documentation, look for "array_walk" and "array_walk_recursive".

Upvotes: 0

Related Questions