简体   繁体   中英

How to store all data with same key together

I have an array which looks like this:

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] => 
        )

)

How can I merge the same keys together, and for all of them add the first value which in this case is 22?

Needed end result:

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
        )

)

I've tried multiple things but nothing gives me the desired result.

Before when I had only two values I did this:

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

But I cannot get it to work for more than 2 values. The array just shows empty when I print it.

I've also tried multiple combinations of the code below:

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 also didn't do what I need.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM