2

I have an array already existing. Lets say it has 3 items.

$user = array('people' => 5, 'friends' => 10, 'siblings' => 7);

I can then access this array like,

echo $user['people']; // 5
echo $user['friends']; // 10

Now lets say I have another array called $person like,

array(3) { 
           [0]=> array(2) 
         { [0]=> string(4) "people" [1]=> string(1) "30" } 
           [1]=> array(2) 
         { [0]=> string(6) "friends" [1]=> string(1) "22" } 
           [2]=> array(2) 
         { [0]=> string(10) "siblings" [1]=> string(1) "71" }
         }

I can access my $user array by using the second array $person manually by doing.

 echo $user[$person[0][0]]; // Is accessing $user['people'], 5
 echo $user[$person[0][1]]; // Is accessing $user['friends'], 10
 echo $user[$person[0][2]]; // Is accessing $user['siblings'], 7

How can I do this dynamically (as the $person arrays keys can change)? Let us say to use it in a function like so,

max($user[$person[0][0]], $user[$person[0][1]], $user[$person[0][2]]) // 10

If this possible?

cgwebprojects
  • 3,382
  • 6
  • 27
  • 40

3 Answers3

2

use a foreach() :

foreach($person as $key => $value)
{
  echo $value[$key];
}
Zul
  • 3,627
  • 3
  • 21
  • 35
  • And how would I go about dynamically adding it to the max function, that is where I am stuck at. The array `$person` could have as many keys as 100. – cgwebprojects Jan 23 '12 at 18:32
  • 1
    @cgwebprojects The `max()` function takes either a set of arguments or one array argument - so you would just build a temporary array and pass that to `max()` – DaveRandom Jan 23 '12 at 18:37
  • @cgwebprojects: you can find here: http://stackoverflow.com/questions/5846156/get-min-and-max-value-in-php-array – Zul Jan 23 '12 at 18:38
1

A more robust solution than a foreach hard-coded for a two-dimensional array would be PHP's built-in RecursiveArrayIteratordocs:

$users = array(
  array('people' => 5, 'friends' => 10, 'siblings' => 7),
  array('people' => 6, 'friends' => 11, 'siblings' => 8),
  array('people' => 7, 'friends' => 12, 'siblings' => 9)
);

$iterator = new RecursiveArrayIterator($users);

while ($iterator->valid()) {
  if ($iterator->hasChildren()) {
    // print all children
    foreach ($iterator->getChildren() as $key => $value) {
      echo $key . ' : ' . $value . "\n";
    }
  } else {
    echo "No children.\n";
  }
  $iterator->next();
}
0

Try using a foreach loop with $user[$person[0]] as the array parameter. If you want to go through both levels of the multidimensional array, you can nest a foreach inside of another foreach

Kristian
  • 21,204
  • 19
  • 101
  • 176