使用foreach键值从PHP数组中获取特定值

时间:2014-06-02 11:41:19

标签: php arrays foreach

我有以下数组:

array(15) { 
    [0]=> object(stdClass)#317 (2) { ["id"]=> string(1) "2" ["value"]=> string(1) "1" } 
    [1]=> object(stdClass)#316 (2) { ["id"]=> string(1) "3" ["value"]=> string(531) "awfaww" }   
    [2]=> object(stdClass)#315 (2) { ["id"]=> string(1) "4" ["value"]=> string(1) "1" } 
    [3]=> object(stdClass)#318 (2) { ["id"]=> string(1) "5" ["value"]=> string(1) "1" } 
    [4]=> object(stdClass)#319 (2) { ["id"]=> string(1) "6" ["value"]=> string(1) "1" } 
    [5]=> object(stdClass)#320 (2) { ["id"]=> string(1) "7" ["value"]=> string(1) "1" } 
    [6]=> object(stdClass)#321 (2) { ["id"]=> string(1) "8" ["value"]=> string(1) "1" } 
    [7]=> object(stdClass)#322 (2) { ["id"]=> string(2) "30" ["value"]=> string(8) "12:30:02" }
    [8]=> object(stdClass)#323 (2) { ["id"]=> string(2) "31" ["value"]=> string(8) "18:12:00" }
    [9]=> object(stdClass)#324 (2) { ["id"]=> string(2) "11" ["value"]=> string(10) "2014-06-17" } 
    [10]=> object(stdClass)#325 (2) { ["id"]=> string(2) "12" ["value"]=> string(10) "2014-06-26" } 
    [11]=> object(stdClass)#326 (2) { ["id"]=> string(2) "14" ["value"]=> string(1) "2" }       
    [12]=> object(stdClass)#327 (2) { ["id"]=> string(2) "15" ["value"]=> string(1) "2" } 
    [13]=> object(stdClass)#328 (2) { ["id"]=> string(2) "16" ["value"]=> string(1) "4" } 
    [14]=> object(stdClass)#329 (2) { ["id"]=> string(2) "17" ["value"]=> string(1) "5" } 
} 

我想使用ID从此数组中获取特定值。例如,如果在数组中找到ID:11,我想要检索其值。我怎么能这样做?

3 个答案:

答案 0 :(得分:0)

尝试这样的事情:

<?php
function findById($array, $id) {
    foreach ($array as $value) {
        if ($value->id == $id) {
            return $value->value;
        }
    }
    return null;
}
$result = findById($yourArray, 11);
?>

答案 1 :(得分:0)

如果每次运行数组都是静态的 - 我建议将数组更改为“key”=&gt;“value”数组,使用:

$new_arr = array();
foreach($original_array as $object) {
    $new_arr[$object->id] = $object->value;
}

然后你可以使用$new_arr[id],而不是每次都搜索整个原始数组。

答案 2 :(得分:0)

您可以使用array_filter

array_filter($arr, function($i) { return $i->id == '11'; });

请参阅Documentation