通过制作键和值来合并php数组

时间:2017-01-02 10:21:51

标签: php arrays

[0] => Array
    (
        [0] => Member ID
        [1] => Name
        [2] => Age
        [3] => Relationship
        )

[1] => Array
    (
        [0] => 1001
        [1] => Swift
        [2] => 34
        [3] => Policy Holder
    )

[2] => Array
    (
        [0] => 5259
        [1] => John
        [2] => 31
        [3] => Son
    )

我有一个类似于上面的数组,我想以这样的方式合并它,使得数组索引0中的值成为一个数组,并将值作为其他索引的值,如

Member ID ('1001', '5259'),  
 Name ('Swift', 'John'), 
  Age ('34','31') and 
  Relationship ('Policy Holder','Son').

我已尝试过array_merge但无法得到理想的结果,array_combine也遇到了问题。

1 个答案:

答案 0 :(得分:1)

此特定任务没有读取使用功能。具体而言,如何处理该组数据的逻辑是任意的。所以你必须以某种方式描述如何处理这些数据......

你必须创建自己的例程。看看这个简单的例子:

<?php
$output = [];
$input = [
    [
        'Member ID',
        'Name',
        'Age',
        'Relationship',
    ],
    [
        1001,
        'Swift',
        34,
        'Policy Holder',
    ],
    [
        5259,
        'John',
        31,
        'Son',
    ]
];

$keys = array_shift($input);
foreach ($input as $set) {
    foreach ($set as $index=>$value) {
        $output[$keys[$index]][] = $value;
    }
}

var_dump($output);

输出显然是:

array(4) {
  'Member ID' =>
  array(2) {
    [0] =>
    int(1001)
    [1] =>
    int(5259)
  }
  'Name' =>
  array(2) {
    [0] =>
    string(5) "Swift"
    [1] =>
    string(4) "John"
  }
  'Age' =>
  array(2) {
    [0] =>
    int(34)
    [1] =>
    int(31)
  }
  'Relationship' =>
  array(2) {
    [0] =>
    string(13) "Policy Holder"
    [1] =>
    string(3) "Son"
  }
}