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,656
  • 11
  • 55
  • 82

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
  • 669,327
  • 51
  • 454
  • 560
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
  • 22,590
  • 37
  • 154
  • 291
0

Try this:

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