如何在PHP的数组中找到特定值

时间:2017-05-25 01:06:43

标签: php multidimensional-array

您好我是PHP的新手,想知道如何在同一个数组中找到特定的tokentoken_time。例如,如何在下面的数组中找到token440745553780011a38b207466e2dae1a以及token_time1495672355并显示它们?

阵列

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

2 个答案:

答案 0 :(得分:2)

令人惊讶的是,您可以像往常一样使用array_search()但使用数组:

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

$id将包含两个值都存在的数组的id。然后,您可以像这样访问它:

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

这些术语甚至不需要在正确的顺序中或在针阵列中输入:

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

答案 1 :(得分:1)

这是一个完成你需要的功能:

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

以下是如何使用它:

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