简体   繁体   中英

How can I find specific values in an array for PHP

Hello I am fairly new to PHP and was wondering how can I find a specific token and token_time in the same array. For example, how can I find the token value 440745553780011a38b207466e2dae1a as well as the token_time value 1495672355 in the array below and have them displayed?

Array

array (size=1)
  'token' => 
    array (size=4)
      0 => 
        array (size=2)
          'token' => string '04a1dd0991b366fdc4d7d46fcff03cb3' (length=32)
          'token_time' => int 1495672339
      1 => 
        array (size=2)
          'token' => string '80d84dc863cbbeaef0c9a448f7865352' (length=32)
          'token_time' => int 1495672345
      2 => 
        array (size=2)
          'token' => string '440745553780011a38b207466e2dae1a' (length=32)
          'token_time' => int 1495672355
      3 => 
        array (size=2)
          'token' => string '766ac765d2a34e01cd954444d5895208' (length=32)
          'token_time' => int 1495672525

Surprisingly, you can just simply use array_search() as you normally would but with an array:

$id = array_search([
    'token' => '440745553780011a38b207466e2dae1a',
    'token_time' => 1495672355
], $array['token']);

$id will contain the id of the array where both values are present. You can then access it like this:

$array['token'][$id];

The terms don't even need to be in the right order or type in the needle array:

$id = array_search([
    'token_time' => '1495672355', //passed as string, whereas array has these as ints
    'token' => '440745553780011a38b207466e2dae1a'
], $array['token']);

Here is a function that accomplishes what you need:

function findToken(&$array, $token, $time){
    foreach($array['token'] as $data){
        if($data['token'] == $token && $data['token_time'] == $time){
            return $data;
        }
    }
    return null;
}

Here's how to use it:

$token = findToken($array, '440745553780011a38b207466e2dae1a', '1495672355');
if($token){
    echo "Found token";
} else {
    echo "Token not found";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM