dongzhi9574 2014-07-09 10:13
浏览 269
已采纳

将一个数组拆分为两个

I have an array of date like this

Array
(
    [0] => Array
        (
            [imageName] => WNgrRdqZ
            [alt] => alt text
        )

    [1] => Array
        (
            [imageName] => xoPS0udB
            [alt] => Alt
        )

)

And I'm wanted to format it so I get one array of imageNames, and one array of alt. I can do this simply with a foreach loop, but I'm curious if there's a build in PHP function I could use instead of rewriting something else. I've not found anything useful yet in the PHP manual.

EDIT: It could also be split into 1 array with 2 sub arrays, e.g.

Array
    (
        ['imageName'] => Array(..),
        ['alt'] => Array(...)
    )
  • 写回答

3条回答 默认 最新

  • duanpo2813 2014-07-09 10:17
    关注

    You can use array_column():

    $imageName = array_column($Array, 'imageName');
    $alt = array_column($Array, 'alt');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • dounai1986 2014-07-09 10:22
    关注

    You can use array_reduce:

    <?php
    
    $data = array
    (
        array
        (
            'imageName' => 'WNgrRdqZ',
            'alt' => 'alt text'
        ),
    
        array
        (
            'imageName' => 'xoPS0udB',
            'alt' => 'Alt'
        )
    );
    
    
    $reduced = array_reduce($data,function($carry, $item){
        $carry['imageName'][] = $item['imageName'];
        $carry['alt'][] = $item['alt'];
        return $carry;
    },array());
    
    print_r($reduced);
    

    Working example https://ideone.com/48JXvL

    评论
  • dougou3871 2014-07-09 10:24
    关注

    please review this code

    <?php
    $arraystest = array(0 => array('imageName' => 'WNgrRdqZ', 'alt' => 'alt text'), 1 => array('imageName' => 'xoPS0udB', 'alt' => 'Alt'));
    $i = 0;
    $newarray = array();
    foreach ($arraystest as $item) {
        $newarray['imagename'][$i] = $item['imageName'];
        $newarray['alt'][$i] = $item['alt'];
        $i++;
    }
    
    print_r($newarray);
    exit;
    ?>
    
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 spyder运行重复
  • ¥15 有偿做一个PUBG识别枪械配合罗技宏的
  • ¥15 我考考你,这代码是对的还是错的?
  • ¥15 我用C语言easyx图形库绘制了一个3d游戏方框透视,但进入游戏时候鼠标准星对准方框边缘 鼠标光标就会弹出来这是啥情况怎样让光标对准绘制的方框点击鼠标不弹出光标好烦这样
  • ¥20 用Power Query整合的问题
  • ¥20 基于python进行多背包问题的多值编码
  • ¥15 相同型号电脑与配置,发现主板有一台貌似缺少了好多元器件似的,会影响稳定性和使用寿命吗?
  • ¥15 C语言:数据子序列基础版
  • ¥20 powerbulider 导入excel文件,显示不完整
  • ¥15 paddle训练自己的数据loss降不下去