![](/img/trans.png)
[英]How to create a new array from an existing array such that all data of same index will be together under that index key?
[英]How to store all data with same key together
我有一個看起來像這樣的數組:
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));
}
}
但是我不能讓它用於兩個以上的值。 當我打印該數組時,它顯示為空。
我還嘗試了以下代碼的多種組合:
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
也沒有做我所需要的。
$new_array = [];
foreach ($useroutput['userid'] as $key => $val) {
$new_array[] = [
'companyid' => $useroutput['companyid'],
'userid' => $val,
'username' => $useroutput['username'][$key],
'password' => $useroutput['password'][$key],
];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.