如何使用相同的密钥一起存储所有数据

时间:2018-08-22 15:18:48

标签: php arrays

我有一个看起来像这样的数组:

Array
(
    [companyid] => 22
    [userid] => Array
        (
            [0] => 60
            [1] => 61
            [2] => 65
            [3] => 63
            [4] => 64
            [5] => 66
            [6] => 68
            [7] => 69
            [8] => 70
            [9] => 71
        )

    [username] => Array
        (
            [0] => nu1234
            [1] => nu12345
            [2] => username1235
            [3] => testtttttt
            [4] => username123
            [5] => nu123
            [6] => nu
            [7] => sdgsdgsdg
            [8] => testtttttt1234
            [9] => nu1235678910
            [10] => 
        )

    [password] => Array
        (
            [0] => 
            [1] => 
            [2] => 
            [3] => 
            [4] => 
            [5] => 
            [6] => 
            [7] => 
            [8] => 
            [9] => 
            [10] => 
        )

)

如何将相同的键合并在一起,并为所有键添加第一个值(在这种情况下为22)?

所需的最终结果:

Array
(
    [0] => Array
        (
            [companyid] => 22
            [userid] => 35
            [username] => dfhdfhdf
            [password] => dfhdfhdfhdf
        )

    [1] => Array
        (
            [companyid] => 22
            [userid] => 35
            [username] => dfhdfhdf
            [password] => dfhdfhdfhdf
        )

    [2] => Array
        (
            [companyid] => 22
            [userid] => 35
            [username] => dfhdfhdf
            [password] => dfhdfhdfhdf
        )

)

我已经尝试了多种方法,但是没有什么能给我想要的结果。

在只有两个值之前,我先这样做:

foreach($useroutput['username'] as $key => $val){
  if(!empty($val)){
    $users[] = array_combine(['username','password'],array_column($useroutput, $key));
  }
}

但是我不能让它用于2个以上的值。当我打印该数组时,它显示为空。

我还尝试了以下代码的多种组合:

foreach($useroutput as $key => $val){
  $newarray[$key][]['companyid'] = $useroutput['companyid'];
  $newarray[$key][]['userid'] = $useroutput['userid'];
  $newarray[$key][]['username'] = $useroutput['username'];
  $newarray[$key][]['password'] = $useroutput['password'];
}

array_merge也没有满足我的要求。

1 个答案:

答案 0 :(得分:5)

$new_array = [];
foreach ($useroutput['userid'] as $key => $val) {
    $new_array[] = [
        'companyid' => $useroutput['companyid'],
        'userid' => $val,
        'username' => $useroutput['username'][$key],
        'password' => $useroutput['password'][$key],
    ];
}