简体   繁体   English

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

[英]Get specific value from PHP array using foreach key value

I have the following array: 我有以下数组:

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" } 
} 

I would like to get a specific value from this array using the ID. 我想使用ID从此数组中获取特定值。 For example, if the ID: 11 is found in the array I want to retrieve its value. 例如,如果在数组中找到ID:11,则要检索其值。 How can I do this? 我怎样才能做到这一点?

Try something like this: 尝试这样的事情:

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

if the array is static for each run - i'd suggest changing the array into "key"=>"value" array, using this: 如果数组在每次运行时都是静态的-我建议使用以下方法将数组更改为“ key” =>“ value”数组:

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

and then you can just use $new_arr[id] , instead of searching the whole original array each time. 然后您可以只使用$new_arr[id] ,而不是每次都搜索整个原始数组。

You can use array_filter : 您可以使用array_filter

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

See Documentation 请参阅说明文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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