简体   繁体   中英

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. For example, if the ID: 11 is found in the array I want to retrieve its value. 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:

$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.

You can use array_filter :

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

See Documentation

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