How to find value in array compared to another one

被刻印的时光 ゝ 提交于 2021-02-17 05:39:05

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!