I have two arrays one for keys and another for values. The values array is an array of array.
Keys array:
$keyArray = array("clientId","clientName","clientAdsress","clientPhone");
Values array:
$valuesArray = array(
"0"=>array("1001","aaaaa","ddddddd","22222222"),
"1"=>array("1002","bbbbbb","ddddddd","11111111"),
"2"=>array("1003","ccccc","ddddddd","33333333")
);
Expected Output:
$finalData = array(
"clientId"=>array("1001","1002","1003"),
"clientName"=>array("aaaaa","bbbbbb","ccccc"),
"clientAdsress"=>array("ddddddd","ddddddd","ddddddd"),
"clientPhone"=>array("22222222","11111111","33333333")
);
I have tried this code:
$finalData = array();
for($i=0;$i<count($keyArray);$i++){
for($j=0;$j<count($valuesArray);$j++){
$rowArray = $valuesArray[$j];
$finalData[$keyArray[$i]] = array($rowArray[$i]);
}
}
echo '<pre>';print_r($finalData);echo '</pre>';
Output:
Array
(
[clientId] => Array
(
[0] => 1003
)
[clientName] => Array
(
[0] => ccccc
)
[clientAdsress] => Array
(
[0] => ddddddd
)
[clientPhone] => Array
(
[0] => 33333333
)
)
I am getting the last values of arrays. How can I get my expected output?
To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.
An associative array can be declared in bash by using the declare keyword and the array elements can be initialized at the time of array declaration or after declaring the array variable. The following script will create an associative array named assArray1 and the four array values are initialized individually.
There are two ways to create an associative array.
A simple foreach
solution:
https://3v4l.org/gbBad
<?php
$keyArray = array("clientId", "clientName", "clientAdsress", "clientPhone");
$valuesArray = array(
"0" => array("1001", "aaaaa", "ddddddd", "22222222"),
"1" => array("1002", "bbbbbb", "ddddddd", "11111111"),
"2" => array("1003", "ccccc", "ddddddd", "33333333")
);
$expected = array(
"clientId" => array("1001", "1002", "1003"),
"clientName" => array("aaaaa", "bbbbbb", "ccccc"),
"clientAdsress" => array("ddddddd", "ddddddd", "ddddddd"),
"clientPhone" => array("22222222", "11111111", "33333333")
);
$result = [];
foreach ($keyArray as $key => $keyName) {
foreach ($valuesArray as $value) {
$result[$keyName][] = $value[$key];
}
}
var_dump($result === $expected);
Output for 7.1.25 - 7.3.2
bool(true)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With