doxn43207 2016-06-05 02:44
浏览 15
已采纳

从键和某些子数组值创建数组的简单方法?

I have a source array that looks like this:

$data = array(
    'foo' => array(
        'bar' => 'foo_bar',
        'baz' => 'foo_baz'
    ),
    'fizz' => array(
        'bar' => 'fizz_bar',
        'baz' => 'fizz_baz'
    )
);

I would like to create another array by selecting a key: bar or baz, which will return all of the root keys with the values of the specified key?

some_function($data, 'bar') == array(
    'foo' => 'foo_bar',
    'fizz' => 'fizz_bar'
);

Is there a built-in php function(s) to generate the following results without doing my own loops?

  • 写回答

1条回答 默认 最新

  • dongzaocheng3214 2016-06-05 02:52
    关注
    $data = array(
        'foo' => array(
            'bar' => 'foo_bar',
            'baz' => 'foo_baz'
        ),
        'fizz' => array(
            'bar' => 'fizz_bar',
            'baz' => 'fizz_baz'
        )
    );
    

    To select bar:

    $result = array_combine(
        array_keys($data),
        array_column($data, 'bar')
    );
    

    Here's an example:

    php > var_dump(array_combine(array_keys($data), array_column($data, 'bar')));
    array(2) {
      ["foo"]=>
      string(7) "foo_bar"
      ["fizz"]=>
      string(8) "fizz_bar"
    }
    

    Note that array_column() was introduced in PHP 5.5.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 TMC2209串口模式下读取不到寄存器的值串口助手蓝色字体是发过去的消息,绿色字体是收到的消息,第二行发送读取寄存器的指令但是没有读取到寄存器的值串口助手如下图:接线如下图,如何解决?
  • ¥30 itest不允许查看成绩怎么办
  • ¥15 高通安卓11提取完整线刷包软件,或者优博讯dt50顺丰刷机包
  • ¥20 C,有个译码器,换了信道就跑不出原来数据
  • ¥15 MIMIC数据库安装问题
  • ¥60 基于JTag协议开发Fpga下载器上位机,哪位大🐂有偿指导?
  • ¥20 全书网Java爬取数据
  • ¥15 怎么获取红包封面的原始链接,并且获取红包封面序列号
  • ¥100 微信小程序跑脚本授权的问题
  • ¥100 房产抖音小程序苹果搜不到安卓可以付费悬赏