【问题标题】:2 dimension array to multiple 1 dimension arrays with keys二维数组到多个带键的一维数组
【发布时间】:2021-06-03 01:29:16
【问题描述】:

我的数组:

Array
(
[patient_id] => Array
        (
            [0] => 23
            [1] => 24
            [2] => 25
        )

[fullname] => Array
    (
        [0] => Jhon Sena
        [1] => Mary Sena 
        [2] => Carter Sena
    )

[type] => Array
    (
        [0] => pdf
        [1] => pdf
        [2] => pdf
    )

[textarea_text] => Array
    (
        [0] => text
        [1] => text2
        [2] => text3
        )

)

我想得到什么:

Array
(
    [patient_id] => 23
    [fullname] => Jhon Sena
    [type] => pdf
    [textarea_text] => text
)
Array
(
    [patient_id] => 24
    [fullname] => Mary Sena
    [type] => pdf
    [textarea_text] => text2
)    
Array
    (
    [patient_id] => 25
    [fullname] => Carter Sena
    [type] => pdf
    [textarea_text] => text3
)

我一直在尝试在另一个问题中指出这里的许多 php flatten array 函数,但我无法得到想要的结果,你能指出我正确的方向吗?

例如这个展平功能:

function flatten($ar) {
        $toflat = array($ar);
        $res = array();

        while (($r = array_shift($toflat)) !== NULL) {
            foreach ($r as $v) {
                if (is_array($v)) {
                    $toflat[] = $v;
                } else {
                    $res[] = $v;
                }
            }
        }

        return $res;
    }

没有键就给我这个结果:

    Array
(
    [0] => 23
    [1] => 24
    [2] => 25
    [3] => Jhon Sena
    [4] => Mary Sena
    [5] => Carter Sena
    [6] => pdf
    [7] => pdf
    [8] => pdf
    [9] => text
    [10] => text2
    [11] => text3
)

..................

【问题讨论】:

  • 我一直在尝试使用其他问题中指出的许多 php flatten array 函数 ->然后请在您的问题中发布您尝试的代码,让我们相信您你真的试过了。
  • 问题是你真的不想简单地把它弄平。您需要一个自定义函数来根据您的规范构建新数组(其中内部数组中的每个数字索引都表示结果中同一子数组的一个元素)。
  • 我已经编辑了帖子,并举例说明了我正在做的事情

标签: php arrays codeigniter


【解决方案1】:

你可以通过简单的foreach()来做到这一点

$fialArray = [];

foreach($array as $key=>$value){
    foreach($value as $k=>$val){
        $fialArray[$k][$key] = $val;
    }
}

print_r($fialArray);

输出:https://3v4l.org/qqgp7

【讨论】:

  • @elgranchuchu 很高兴为您提供帮助。请查看已编辑的解决方案。现在效率更高了
猜你喜欢
  • 1970-01-01
  • 2011-10-18
  • 1970-01-01
  • 2011-07-23
  • 2013-11-23
  • 2022-12-07
  • 2021-12-31
  • 2013-05-28
  • 1970-01-01
相关资源
最近更新 更多