I have an array where I want to search if there is certain information.
In case it exists I want to save all the data in variables
I am trying to do it with in_array but I can't find the information.The search I need to do with coords. If it exists "60:58" in array I save the 3 values in variables.
How could I get it? Thanks a lot of!!
array(5) {
[0]=>
object(stdClass)#3 (3) {
["coords"]=>
string(5) "60:58"
["city"]=>
string(5) "spain"
["name"]=>
string(11) "player"
}
[1]=>
object(stdClass)#4 (3) {
["coords"]=>
string(5) "60:59"
["city"]=>
string(5) "spain"
["name"]=>
string(11) "player"
}
}
<?php
$a = [];
$a[] = (object)[
'coords' => '60:58'
];
$a[] = (object)[
'coords' => '13:37'
];
$index = array_search('60:58', array_column($a, 'coords'));
if($index === false) {
// not found
} else {
$var = $a[$index];
var_dump($var);
}
You can filter out everything that does not meet your criteria. Then you either have an empty array or one or more objects matching the criteria. I use reset
to get the first if there are more than one:
$find = '60:58';
$result = reset(array_filter($array, function($v) use($find) { return $v->coords == $find; }));
If there is only one or you only require one, then you can index on coords
. If not found then this will generate a notice so check if it exist (this requires PHP >= 7 since we are using objects):
$result = array_column($array, null, 'coords')[$find];
you have to loop over the array of objects and check if coords match with the value you want
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.