【问题标题】:Check if associative array contains value, and retrieve key / position in array检查关联数组是否包含值,并检索数组中的键/位置
【发布时间】:2014-09-05 18:07:08
【问题描述】:

我正在努力解释我想在这里做什么,如果我让你感到困惑,请道歉.. 我自己也很困惑

我有一个这样的数组:

$foo = array(
    array('value' => 5680, 'text' => 'Red'), 
    array('value' => 7899, 'text' => 'Green'), 
    array('value' => 9968, 'text' => 'Blue'), 
    array('value' => 4038, 'text' => 'Yellow'),
)

我想检查数组是否包含值,例如7899 并在上面的示例中获取链接到该值“Green”的文本。

【问题讨论】:

  • foreach() 呢? ...
  • 7899 未链接到“黄色”。你到底要做什么?
  • @rack_nilesh 为那个 rack_nilesh 道歉.. 解决了这个问题。
  • @Phantom 我想过,但我已经嵌套在其他 2 个 foreach 循环中,想知道是否有更好的方法。

标签: php arrays associative-array associative


【解决方案1】:

试试这样的

$foo = array(
    array('value' => 5680, 'text' => 'Red'), 
    array('value' => 7899, 'text' => 'Green'), 
    array('value' => 9968, 'text' => 'Blue'), 
    array('value' => 4038, 'text' => 'Yellow'),
);

$found = current(array_filter($foo, function($item) {
    return isset($item['value']) && 7899 == $item['value'];
}));

print_r($found);

哪些输出

Array
(
    [value] => 7899
    [text] => Green
)

这里的关键是array_filter。如果搜索值7899 不是静态的,那么您可以使用function($item) use($searchValue) 之类的内容将其带入闭包。请注意,array_filter 正在返回一个元素数组,这就是为什么我将它传递给 current

【讨论】:

  • 旁注:动态搜索值$found = current(array_filter($activityArray, function($item) use($jobID) { return isset($item['jobid']) && $jobID == $item['jobid']; })); print_r($found);
【解决方案2】:

对于 PHP >= 5.5.0,使用array_column 会更容易:

echo array_column($foo, 'text', 'value')[7899];

或者是可重复的,无需每次都使用array_column

$bar = array_column($foo, 'text', 'value');
echo isset($bar[7899]) ? $bar[7899] : 'NOT FOUND!';

【讨论】:

    【解决方案3】:

    在这里猜一猜你想要什么:

    function findTextByValueInArray($fooArray, $searchValue){
        foreach ($fooArray as $bar )
        {
            if ($bar['value'] == $searchValue) {
                return $bar['text'];
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-03
      • 2019-08-10
      • 2017-05-28
      • 2021-08-19
      • 1970-01-01
      • 2015-01-01
      • 2021-07-15
      相关资源
      最近更新 更多