【问题标题】:Get the value of array1 specifing the value of the array inside the values of array1 [duplicate]获取array1的值,指定array1的值内的数组值[重复]
【发布时间】:2017-09-25 06:35:50
【问题描述】:

我认为从标题上看不太清楚,但情况是这样的:

我有一个像这样的数组(它更大,这只是一个例子):

$array = array(
    array('name' => 'John', 'age' => '29', 'from' => 'Uknown'),
    array('name' => 'Brad', 'age' => '27', 'from' => 'Idk'),
    array('name' => 'Phil', 'age' => '31', 'from' => 'My House')
);

我正在尝试使用 PHP 的本机函数(不使用循环或其他东西)找到​​一种快速方法,该方法在另一个数组中指定该数组的名称,它会返回与该名称相关的信息。

例子:

如果我指定Brad,它会返回一个数组:

array('name' => 'Brad', 'age' => '27', 'from' => 'Idk')

【问题讨论】:

  • 如果不检查名称字段,我认为您无法做到这一点。即使有一个本机函数,它也会在引擎盖下使用循环
  • 你说得对,我在消息中不是很清楚。我的意思是当有一种使用 PHP 的原生函数更简洁、更容易的方法时,不使用循环并执行一个新函数。

标签: php arrays multidimensional-array


【解决方案1】:

这是我的方法

$key = array_search('Brad', array_column($array, 'name'));

print_r($array[$key]);

供参考
PHP docs : array-search
PHP docs : array-column

【讨论】:

    【解决方案2】:

    假设您没有重复的项目和重复的名称。

    $names = array_column($array, 'name');
    $indexs = array_flip($names);
    print_r($array[$indexs['Brad']]);
    

    【讨论】:

      【解决方案3】:

      没有这样的功能。您唯一的选择是将数组重建为:

      $array = array(
          'John' => array('name' => 'John', 'age' => '29', 'from' => 'Uknown'),
          'Brad' => array('name' => 'Brad', 'age' => '27', 'from' => 'Idk'),
          'Phil' => array('name' => 'Phil', 'age' => '31', 'from' => 'My House')
      );
      

      并使用简单的isset:

      if (isset($array['Brad'])) {
          print_r($array['Brad']);
      } else {
          echo 'Brad not found';
      }
      

      当然,如果name 值在您的数组中重复,您必须创建更多唯一键。

      【讨论】:

      • 是的......而且你不必重建任何东西
      • @VikingCode 隐藏循环,好吧。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-31
      • 1970-01-01
      • 2012-02-20
      • 2020-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多