在PHP中,有一个返回由来自关联数组的数组的键值数组的功能? [英] In PHP, is there a function that returns an array made up of the value of a key from an array of associative arrays?

查看:442
本文介绍了在PHP中,有一个返回由来自关联数组的数组的键值数组的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我敢肯定,这个问题已经被问过,我的道歉不先找到它。

原始数组:

  [0] =>排列
    (
        [的categoryId] => 1
        [事件ID] => 2
        [eventName的] => 3
        [VENDORNAME] => 4
    )[1] =>排列
    (
        [的categoryId] =>五
        [事件ID] => 6
        [eventName的] => 7
        [VENDORNAME] => 8
    )[2] =>排列
    (
        [的categoryId] => 9
        [事件ID] => 10
        [eventName的] => 11
        [VENDORNAME] => 12
    )

我希望结果出来:的print_r(get_values​​_from_a_key_in_arrays('的categoryId',$阵列));

  [0] => 1
[1] =>五
[2] => 9

我只是在寻找的东西比我自己写的foreach基于函数的清洁剂。如果是的foreach的回答,我已经有到位。

编辑:我不希望使用硬codeD密钥,我只是展示一个例子调用解决方案。谢谢! ^ _ ^

快速抢解决方案PHP 5.3:

 私有函数勇气($键,$数据){
    返回array_reduce($的数据,功能($结果,$阵列)使用($键){
        使用isset($数组[$关键])及和放大器; $结果[] = $阵列[$关键];
        返回$结果;
    },阵列());
}


解决方案

所以,了解高阶中的很酷的事情收集/迭代器功能如的拔毛过滤,的每个地图,和朋友们的是,它们可以被混合和匹配,以构成一个更复杂的操作集合

大多数语言提供这些类型的函数(看起来像采集,迭代器,或枚举/枚举包)......提供一些比别人更多的功能,你通常会看到该功能是不同的跨语言命名(即收集= =地图,减少==倍)。如果函数不会在你的语言存在,您可以从确实存在的那些创建它。

至于你的测试案例......我们可以使用 array_reduce 实施勇气。第一个版本我贴靠 array_map ;不过,我同意 @salathe array_reduce 是这个任务更加简洁; array_map 是一个不错的选择,但最终不得不在最后做更多的工作。 array_reduce 可有些奇怪在第一,但如果回调井然有序,一切都很好。

一个幼稚少勇气还要检查,看它是否能够在迭代值呼叫(函数/方法)。在下面的幼稚实现中,我们假设结构是一个散列(关联数组)。

这将建立测试用例的数据(照明灯):

 < PHP$数据[] =阵列('的categoryId'=大于1,'EVENTID'=大于2,'eventName的'=→3'VENDORNAME'=→4);
$数据[] =阵列('的categoryId'=大于5,'EVENTID'=→6,'eventName的'=大于7,'VENDORNAME'=→8);
$数据[] =阵列('的categoryId'= GT; 9,'EVENTID'=大于10,'eventName的'=> 11'VENDORNAME'=> 12);
$数据[] =阵列(/ *没有的categoryId * /'EVENTID'=大于10,'eventName的'=> 11'VENDORNAME'=> 12);
$数据[] =阵列('的categoryId'= GT假,EVENTID'=大于10,'eventName的'=> 11'VENDORNAME'=> 12);
$数据[] =阵列('的categoryId'= GT; 0.0,'EVENTID'=大于10,'eventName的'=> 11'VENDORNAME'=> 12);

选择拔毛的版本,你会preFER

  $preferredPluck ='pluck_array_reduce'; //或pluck_array_map

勇气为PHP 5.3+:array_reduce提供了一个简洁的实现虽然不是那么容易的array_map版本推理:

 函数pluck_array_reduce($键,$数据){
  返回array_reduce($的数据,功能($结果,$阵列)使用($键){
    使用isset($数组[$关键])及和放大器;
      $结果[] = $阵列[$关键];    返回$结果;
  },阵列());
}

勇气为PHP 5.3+:array_map不适合这个,所以我们必须做更多的检查(它仍然不能解释许多潜在的情况下):

 函数pluck_array_map($键,$数据){
  $图= array_map(函数($数组)使用($键){
    返回使用isset($数组[$关键])? $阵列[$关键]:空;
  } $的数据);  // is_scalar是不完美的;使这个适合你,你可能需要调整
  返回array_filter($地图,'is_scalar');
}

勇气遗留PHP< 5.3

我们也可以使用传统 create_function ;但是,它是坏的形式,而不是推荐,也没有在所有的优雅,因此,我决定不表现出来。

 函数pluck_compat($键,$数据){
  $图=阵列();
  的foreach($作为数组$的数据){
    如果(array_key_exists($键,$阵列)){
      $映射[] = $阵列[$关键];
    }
  }
  未设置($数组);  返回$图;
}

在这里我们选择一个版本,采摘的基础上,我们正在运行的PHP版本调用。如果运行整个脚本,你应该得到正确的答案,不管你是什么版本。

  $ =实际version_compare(PHP_VERSION,'5.3.0','> =')
          ? $preferredPluck('的categoryId',$数据)
          :pluck_compat('的categoryId',$数据);
$预期=阵列(1,5,9日,假,0.0);
$差异=计数(和array_diff($预期,实际$));后续代码var_dump($预期,$实际);
回声PHP_EOL;
回声方差:',$方差PHP_EOL;打印@assert($方差)
    ? 断言失败
    :断言传递';

注意没有结束?>。这是因为它不需要。更多的好可以来留下这又比从保持它周围的人。

FWIW,它看起来像这样被添加到PHP 5.5的<一个href=\"http://benramsey.com/blog/2013/03/introducing-array-column-in-php-5-dot-5/\">array_column.

I'm sure this question has been asked before, my apologies for not finding it first.

The original array:

[0] => Array
    (
        [categoryId] => 1
        [eventId] => 2
        [eventName] => 3
        [vendorName] => 4
    )

[1] => Array
    (
        [categoryId] => 5
        [eventId] => 6
        [eventName] => 7
        [vendorName] => 8
    )

[2] => Array
    (
        [categoryId] => 9
        [eventId] => 10
        [eventName] => 11
        [vendorName] => 12
    )

My hoped for result out of: print_r(get_values_from_a_key_in_arrays('categoryId', $array));

[0] => 1
[1] => 5
[2] => 9

I'm just looking for something cleaner than writing my own foreach based function. If foreach is the answer, I already have that in place.

Edit: I don't want to use a hard-coded key, I was just showing an example call to the solution. Thanks! ^_^

Quick Grab Solution for PHP 5.3:

private function pluck($key, $data) {
    return array_reduce($data, function($result, $array) use($key) {
        isset($array[$key]) && $result[] = $array[$key];
        return $result;
    }, array());
}

解决方案

So, the cool thing about higher-order collection/iterator functions such as pluck, filter, each, map, and friends is that they can be mixed and matched to compose a more complex set of operations.

Most languages provide these types of functions (look for packages like collection, iterator, or enumeration/enumerable)...some provide more functions than others and you will commonly see that the functions are named differently across languages (i.e. collect == map, reduce == fold). If a function doesn't exist in your language, you can create it from the ones that do exist.

As for your test case...we can use array_reduce to implement pluck. The first version I posted relied on array_map; however, I agree with @salathe that array_reduce is more succinct for this task; array_map is an OK option, but you end up having to do more work in the end. array_reduce can look a bit odd at first, but if the callback is neatly organized, all is well.

A less naive pluck would also check to see if it can "call" (a function/method) on the iterated value. In the naive implementation below, we assume the structure to be a hash (associative array).

This will setup the test-case data (Fixtures):

<?php

$data[] = array('categoryId' => 1,    'eventId' => 2,  'eventName' => 3,  'vendorName' => 4);
$data[] = array('categoryId' => 5,    'eventId' => 6,  'eventName' => 7,  'vendorName' => 8);
$data[] = array('categoryId' => 9,    'eventId' => 10, 'eventName' => 11, 'vendorName' => 12);
$data[] = array(/* no categoryId */   'eventId' => 10, 'eventName' => 11, 'vendorName' => 12);
$data[] = array('categoryId' => false,'eventId' => 10, 'eventName' => 11, 'vendorName' => 12);
$data[] = array('categoryId' => 0.0,  'eventId' => 10, 'eventName' => 11, 'vendorName' => 12);

Choose the version of pluck you'd prefer

$preferredPluck = 'pluck_array_reduce'; // or pluck_array_map

"pluck" for PHP 5.3+: array_reduce provides a terse implementation though not as easy to reason about as the array_map version:

function pluck_array_reduce($key, $data) {
  return array_reduce($data, function($result, $array) use($key){
    isset($array[$key]) &&
      $result[] = $array[$key];

    return $result;
  }, array());
}

"pluck" for PHP 5.3+: array_map isn't perfect for this so we have to do more checking (and it still doesn't account for many potential cases):

function pluck_array_map($key, $data) {
  $map = array_map(function($array) use($key){
    return isset($array[$key]) ? $array[$key] : null;
  }, $data);

  // is_scalar isn't perfect; to make this right for you, you may have to adjust
  return array_filter($map, 'is_scalar');
}

"pluck" for legacy PHP <5.3

We could have used the legacy create_function; however, it is bad form, not recommended, and also not at all elegant, thus, I've decided not to show it.

function pluck_compat($key, $data) {
  $map = array();
  foreach ($data as $array) {
    if (array_key_exists($key, $array)) {
      $map[] = $array[$key];
    }
  }
  unset($array);

  return $map;
}

Here we choose a version of "pluck" to call based on the version of PHP we are running. If you run the entire script, you should get the correct answer no matter what version you are on.

$actual   = version_compare(PHP_VERSION, '5.3.0', '>=')
          ? $preferredPluck('categoryId', $data)
          : pluck_compat('categoryId', $data);
$expected = array(1, 5, 9, false, 0.0);
$variance = count(array_diff($expected, $actual));

var_dump($expected, $actual);
echo PHP_EOL;
echo 'variance: ', $variance, PHP_EOL;

print @assert($variance)
    ? 'Assertion Failed'
    : 'Assertion Passed';

Notice there is no ending '?>'. That is because it isn't needed. More good can come of leaving it off than from keeping it around.

FWIW, it looks like this is being added to PHP 5.5 as array_column.

这篇关于在PHP中,有一个返回由来自关联数组的数组的键值数组的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆