问题
I'm looking for a way to find value in array compared to another one.
Let's assume we have a php array : (I take the one of this question because it's exactly my case)
$userdb = array(
array(
'uid' => '100',
'name' => 'Sandra Shush',
'pic_square' => 'urlof100'
),
array(
'uid' => '5465',
'name' => 'Stefanie Mcmohn',
'pic_square' => 'urlof100'
),
array(
'uid' => '40489',
'name' => 'Michael',
'pic_square' => 'urlof40489'
)
);
What's I need is to know if there's a way to find (for example) the value of name where uid is 100.
I hope to have been clear, thanks for your help :)
回答1:
Yes There is a way,
$temp = array_column($userdb, 'name','uid');
echo ($temp[100] ?? ''); // php 7
echo (!empty($temp[100]) ? $temp[100] : ''); // < php 7
array_column — Return the values from a single column in the input array
Syntax:
array_column ( array $input , mixed $column_key [, mixed $index_key = NULL ] ) : array
Demo.
回答2:
Unless I am overlooking something, this is as simple as iterating through the $userdb
array, looking for the matching value in the uid
field and then storing the resulting name
in a variable:
$name = null;
foreach ($userdb as $user) {
if ($user['uid'] == 100) {
$name = $user['name'];
break;
}
}
var_dump($name);
来源:https://stackoverflow.com/questions/56527099/how-to-find-value-in-array-compared-to-another-one