Convert nested associative array to single array in php [duplicate] - php

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 10 months ago.
I have nested array with key & value pair. i want to convert it in single array.
/* This is current array */
Array
(
[id] => Array
(
[0] => 1
[1] => 2
)
[qty] => Array
(
[0] => 1
[1] => 1
)
[price] => Array
(
[0] => 364.41
[1] => 300
)
[amount] => Array
(
[0] => 364.41
[1] => 300
)
)
/*Now, I want this type of array*/
Array
(
[0] => Array
(
[id] => 1
[qty] => 1
[price] => 364.41
[amount] => 364.41
)
[1] => Array
(
[id] => 2
[qty] => 1
[price] => 300
[amount] => 300
)
)
I have tried array_walk and some other solutions but i could not find any proper solution
Thanks in advance

Main array is your nested array and Collection is the result you want
foreach($mainArray["id"] as $key => $value ){
$collection[$key] = ['id' => $value];
foreach(array_keys($mainArray) as $arrayKeysOfmainArray){
if(!array_key_exists($arrayKeysOfmainArray, $collection)){
$collection[$key][$arrayKeysOfmainArray] = $mainArray[$arrayKeysOfmainArray][$key];
}
}
}
print_r($collection);

$mainarray['id'] = Array(1,2,3);
$mainarray['qty'] = Array(1,1,4);
$mainarray['price'] = Array(364.41,300,500);
$mainarray['amount'] = Array(364.41,300,600);
$new = [];
foreach($mainarray as $key=> $singleArray){
if(count($singleArray) > 0){
foreach($singleArray as $childKey=> $value){
$new[$childKey][$key] = $value;
}
};
}`

Related

I want to change the key of multidimensional array [duplicate]

This question already has answers here:
How do you reindex an array in PHP but with indexes starting from 1?
(12 answers)
Closed 3 years ago.
I want to change the key of the multidimensional array. the array contains key like 1,15,23,45 which should be replaced by normal index key like 0,1,2,3. I tried with below code. Something is missing in below code. Please, anyone, suggest to me.
$keys = array_keys($data);
$d = 0;
foreach($data as $row){
$key_data[$d] = $data[$keys[$d]];
unset($row[$keys[$d]]);
$d++;
}
Current Output
Array
(
[15] => Array
(
[0] => Array
(
[app_dealer_id] => 15
[dealer_name] => Sharad Thombre
[shopname] => Shivshankar Fertilizer
[contact_num] => 9049121143
[district] => Parbhani
)
)
[18] => Array
(
[0] => Array
(
[app_dealer_id] => 18
[dealer_name] => Gajanan Khapre
[shopname] => Shreyas Krishi Kendra
[contact_num] => 8007791946
[district] => Parbhani
)
)
)
Expected Output:
Array
(
[0] => Array
(
[0] => Array
(
[app_dealer_id] => 15
[dealer_name] => Sharad Thombre
[shopname] => Shivshankar Fertilizer
[contact_num] => 9049121143
[district] => Parbhani
)
)
[1] => Array
(
[0] => Array
(
[app_dealer_id] => 18
[dealer_name] => Gajanan Khapre
[shopname] => Shreyas Krishi Kendra
[contact_num] => 8007791946
[district] => Parbhani
)
)
)
use array_values()
$array = array_values($array);
Output:-https://3v4l.org/cUAdl
From php.net :
array_values() returns all the values from the array and indexes the array numerically.
So just add it after your loop to reindex you array :
$keys = array_keys($data);
$d = 0;
foreach($data as $row){
$key_data[$d] = $data[$keys[$d]];
unset($row[$keys[$d]]);
$d++;
}
$newArray = array_keys($key_data);

Convert Multidimensional array to single array in php [duplicate]

This question already has answers here:
Convert multidimensional array into single array [duplicate]
(24 answers)
Closed 5 years ago.
It's probably beginner question but I'm going through documentation for
longer time already and I can't find any solution and i have an array which
is multidimensional given below format.
/* This is how my array is currently */
Array
(
[0] => Array
(
[0] => Array
(
[title] => a
[title_num] =>1
[status] => 1
)
[1] => Array
(
[title] => Mr
[title_num] => 82
[status] => 1
)
)
[1] => Array
(
[0] => Array
(
[title] => b
[title_num] =>25
[status] => 2
)
[1] => Array
(
[title] => c
[title_num] =>45
[status] => 2
)
)
)
I want to convert this array into this form
/*Now, I want to simply it down to this*/
Array
(
[0] => Array
(
[title] => a
[title_num] =>1
[status] => 1
)
[1] => Array
(
[title] => Mr
[title_num] => 82
[status] => 1
)
[2] => Array
(
[title] => b
[title_num] =>25
[status] => 2
)
[3] => Array
(
[title] => c
[title_num] =>45
[status] => 2
)
)
I have tried array_flatten,array_map PHP built in function
A link or anything to point me in the right direction will be highly
appreciated
Here is another trick to solve your problem,
function custom_filter($array) {
$temp = [];
array_walk($array, function($item,$key) use (&$temp){
foreach($item as $value)
$temp[] = $value;
});
return $temp;
}
array_walk — Apply a user supplied function to every member of an array
Here is working demo.
here you go
$result = [];
foreach($array as $arr)
{
$result = array_merge($result , $arr);
}
var_dump($result);
Like this:
$i=0;
foreach ($array as $n1) {
foreach ($n1 as $n2) {
$newArr[$i]['title']=$n2['title'];
$newArr[$i]['title_num']=$n2['title_num'];
$newArr[$i]['status']=$n2['status'];
}
$i++;
}
Or simpler as suggested in the comments
for ($i=0; $i < count($array); $i++) {
foreach ($array[$i] as $n2) {
$newArr[$i]['title']=$n2['title'];
$newArr[$i]['title_num']=$n2['title_num'];
$newArr[$i]['status']=$n2['status'];
}
}

Sort multidimensional array by given key PHP [duplicate]

This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 5 years ago.
I have a multidimensional array that needs to be reoreder, the array look like this :
[products] => Array
(
[149] => Array
(
[name] => Ichikami1
[qty] => 2
)
[150] => Array
(
[name] => Ichikami2
[qty] => 4
)
[377] => Array
(
[name] => BCL
[qty] => 2
)
)
inside the child array there is 'qty' index, i want to sort the child array by 'qty' index in descending order, so it will look like this:
[products] => Array
(
[0] => Array
(
[name] => Ichikami2
[qty] => 4
)
[1] => Array
(
[name] => Ichikami1
[qty] => 2
)
[2] => Array
(
[name] => BCL
[qty] => 2
)
)
is there a way to do this?
Simply by using array_multisort(), You can do this like:
$qty = array();
foreach ($products as $key => $row)
{
$qty[$key] = $row['qty'];
}
array_multisort($qty, SORT_DESC, $products);

Sum values in multidimensional array by key [duplicate]

This question already has answers here:
Group array data on one column and sum data from another column
(5 answers)
Closed 1 year ago.
I have read a lot of answers here on SO but havent been able to sort this out.
I have multidimensional array that looks like this:
Array
(
[0] => Array
(
[0] =>
[1] => 655
)
[1] => Array
(
[0] => IT-82
[1] => 14
)
[2] => Array
(
[0] => IT-21
[1] => 5
)
[3] => Array
(
[0] => IT-82
[1] => 7
)
[4] => Array
(
[0] =>
[1] => 3
)
[5] => Array
(
[0] => IT-21
[1] => 4
)
[6] => Array
(
[0] =>
[1] => 3
)
[7] => Array
(
[0] => IT-21
[1] => 3
)
[8] => Array
(
[0] => IT-72
[1] => 7
)
[9] => Array
(
[0] => IT-75
[1] => 22
)
[10] => Array
(
[0] => IT-75
[1] => 3
)
)
I would like to sum the values according to the keys ending with a single array like:
Array
(
=> 661
IT-82 => 21
IT-21 => 12
IT-82 => 12
IT-72 => 7
IT-75 => 25
)
Tried with
foreach ($array as $k=>$subArray) {
foreach ($subArray as $id=>$value) {
$sumArray[$id]+=$value;
}
}
but this only returned the sum of all the values.
Any help appreciated.
Try:
$sumArray = array();
foreach ($array as $k=>$subArray) { //loop through array
if(isset($sumArray[$subArray[0]]))
$sumArray[$subArray[0]] += $subArray[1]; // set 0th index as key and 1st as value and add value to current index
else
$sumArray[$subArray[0]] = $subArray[1];
}
print_r($sumArray);
Output:
Array
(
[] => 661
[IT-82] => 21
[IT-21] => 12
[IT-72] => 7
[IT-75] => 25
)
I suppose it should be:
foreach ($array as $subArray) {
$sumArray[$subArray[0]] += $subArray[1];
}

Padding a multidimensional array with array_pad?

$summary=$query->result_array(); //where the original array is created
print_r($summary); //dump contents
Produces this:
Array ( [0] => Array ( [RecordID] => 2 [UserID] => 3 [BookID] => 1 [Title] => FirstBook ) [1] => Array ( [RecordID] => 3 [UserID] => 3 [BookID] => 2 [Title] => Sequel ) )
I would now like to pad the multi dimensional array with a price element so as to create the results of
Array ( [0] => Array ( [RecordID] => 2 [UserID] => 3 [BookID] => 1 [Title] => FirstBook [Price] => 99 ) [1] => Array ( [RecordID] => 3 [UserID] => 3 [BookID] => 2 [Title] => Sequel [Price] => 99) )
The only way I can think of doing this is to break the multidimensional array into one-dimensional arrays, modify them, and then re-assemble them. Doesn't sound terribly efficient though. Any suggestions?
You can update the internal arrays by reference, note the & here:
foreach($summary as &$details){
$details['Price'] = $price; // wherever $price comes from...
}
try to use:
foreach ($summary as $idx => &$arrValue)
$arrValue['Price'] = ###;
If you're fixed on your dimensions, iterate with a reference and modify $summary in place...
<?php
foreach ($summary as &item) {
$item['price'] = 99;
}
If you have particular objections/issues with references:
<?php
foreach ($summary as $key=>item) {
$summary[$key]['price'] = 99;
}

Categories