0

I am trying to search an array for a given value. Once I find this value, I need the array key value to access other information in the array. Here is the array I need to search:

array(3) {
  [0]=>
  array(20) {
    ["FirstName"]=>
    string(7) "Person1"
    ["LastName"]=>
    string(7) "Person1"
    ["UserId"]=>
    int(5632414)
  }
  [1]=>
  array(20) {
     ["FirstName"]=>
    string(7) "Person2"
    ["LastName"]=>
    string(7) "Person2"
    ["UserId"]=>
    int(5632414)
  }
  [2]=>
  array(20) {
     ["FirstName"]=>
    string(7) "Person3"
    ["LastName"]=>
    string(7) "Person3"
    ["UserId"]=>
    int(5632414)
  }
}

I am searching the array for a specific UserId. I have tried several bits of code but none seem to work. All I get is a blank screen when I run the script. Here is my most current code:

$array = json_decode($output);

for ($x = 0; $x <= count($array); $x++) {
    $key = array_search('5632414', $array);
    echo $key;
}
three3
  • 2,756
  • 14
  • 57
  • 85
  • 2
    `$array = json_decode($output);` gives an object, not an array. You need to pass `true` as the second parameter to make it one. `$array = json_decode($output, true);` – MisterBla Oct 03 '13 at 22:00
  • It should be `$x < count($array)`, or you'll miss the last element. – StackSlave Oct 03 '13 at 22:04
  • Actually, that should be "or you'll go past the last element". – Barmar Oct 03 '13 at 22:05
  • This question has already been [asked](http://stackoverflow.com/questions/6661530/php-multi-dimensional-array-search). – user1056677 Oct 03 '13 at 22:08

3 Answers3

0

array_search can only be used with one-dimensional arrays. In your case, you're not looking for a string in the top-level array, it's the value of one of the associative sub-arrays.

foreach ($array as $key => $subarray) {
    if ($subarray['UserId'] == 5632414) {
        echo $key;
    }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Judging from the var_dump output you posted, it looks like you could do something like:

$array = json_decode($output);

for ($x = 0; $x < count($array); $x++) {
    if ( $array[ x ][ "UserId" ] === $the_value_I_am_looking_for )
    {
        //Then do something
    }
}
Don Rhummy
  • 24,730
  • 42
  • 175
  • 330
0

Try this:

function findIn($find, $inArray){
  foreach($inArray as $a){
    foreach($a as $i => $v){
      if($v === $find){
        return $i;
      }
    }
  }
}
StackSlave
  • 10,613
  • 2
  • 18
  • 35