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);
Related
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;
}
};
}`
This question already has answers here:
How to remove duplicate values from a multi-dimensional array in PHP
(18 answers)
Closed 2 years ago.
I searched for solutions on here but didn't find one for my use case.
I have a big array which is built like this example:
Array
(
[0] => Array
(
[Template] => page.html5
)
[1] => Array
(
[Template] => page2.html5
)
[2] => Array
(
[Template] => page.html5
)
[3] => Array
(
[Template] => page2.html5
)
[4] => Array
(
[Template] => page.html5
)
[5] => Array
(
[Template] => page2.html5
)
[6] => Array
(
[id] => 27
[table] => tl_custom
[type] => text
[data] => Array
(
[fragment] => example
[previewId] => 1
[isActive] => 1
)
)
)
I would like to remove all duplicate values for the array key "Template", but besides that I want the array to stay the way it is.
So afterwards my Array should look like:
Array
(
[0] => Array
(
[Template] => page.html5
)
[1] => Array
(
[Template] => page2.html5
)
[6] => Array
(
[id] => 27
[table] => tl_custom
[type] => text
[data] => Array
(
[fragment] => example
[previewId] => 1
[isActive] => 1
)
)
)
Is there a way to achieve this without using lots of memory?
Thanks for your answers :)
You could use the following logic, which uses:
array_map() to flatten the array with index keys-values, and serialize() (stringify) the last array element so we can use
array_unique() on the result.
Then, to restore the stringified array, i.e. turn it back into an array, we use unserialize().
<?php
$newArr = array_unique(array_map(function ($el) {
return $el['Template'] ?? serialize($el);
}, $arr));
// restore the last element to array
$last = array_key_last($newArr); // (PHP 7 >= 7.3.0)*
$newArr[$last] = unserialize($newArr[$last]);
*if PHP version <7.3.0 use: end($newArr); $last = key($newArr);
Output:
Array
(
[0] => page.html5
[1] => page2.html5
[6] => Array
(
[id] => 27
[table] => tl_custom
[type] => text
[data] => Array
(
[fragment] => example
[previewId] => 1
[isActive] => 1
)
)
)
working demo
The code below loops the array, marks indexes for removal and then another loop does the removals:
$templates = array(); //This will store the remove plan
for ($index = 0; $index < count($input); $index++) {
if (isset($input[$index]["Template"])) { //Ignore items where there is no template
if (isset($templates[$input[$index]["Template"]])) { //Let's check whether we have already seen this template
$templates[$input[$index]["Template"]] = array(); //From now on we will find duplicates for this dude
} else { //Mark for removal
$templates[$input[$index]["Template"]][]=$index;
}
}
}
//Actual removals
foreach($templates => $index) {
//Removing the actual element:
unset($input[$index]["Template"]);
//Remove the parent as well if it becomes empty
if (!count($input[$index])) unset($input[$index]);
}
The memory need for this algorithm is:
average(element_size) * number_of_elements
This question already has answers here:
Associative array, sum values of the same key
(5 answers)
Closed 3 years ago.
Following is my array. I need to add its Sum field according to each emp_firstname. Some has only one time coming, some coming two times. how can we sum the field and make the array unique?
Array
(
[0] => Array
(
[emp_firstname] => Alistair
[non_pm] => AMZ
[sum] => 2
)
[1] => Array
(
[emp_firstname] => Shakkeer
[non_pm] => SHK
[sum] => 3
)
[2] => Array
(
[emp_firstname] => Waqas
[non_pm] => WAS
[sum] => 12
)
[3] => Array
(
[emp_firstname] => Zain
[non_pm] => ZAI
[sum] => 9
)
[4] => Array
(
[emp_firstname] => Shakkeer
[gud_pmeditor] => SHK
[sum] => 4
)
[5] => Array
(
[emp_firstname] => Zain
[gud_pmeditor] => ZAI
[sum] => 2
)
)
You can get the desired result using this approach
$res=[];
foreach($arr as $val){
if(array_key_exists($val['emp_firstname'], $res))
$res[$val['emp_firstname']]['sum'] = ($res[$val['emp_firstname']]['sum'] + $val['sum']);
else
$res[$val['emp_firstname']] = $val;
}
Live Demo
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];
}
This question already has answers here:
How do you reindex an array in PHP but with indexes starting from 1?
(12 answers)
How to re-index all subarray elements of a multidimensional array?
(6 answers)
Closed 10 months ago.
How do I run a array_map on a triple dimensional array? Where I want to "clear" the innermost array?
It looks like this:
Array
(
[1] => Array
(
[1] => Array
(
[cat] => Hello!
[url] => hello
)
[5] => Array
(
[cat] => Good job!
[url] => good-job
)
[2] => Array
(
[2] => Array
(
[cat] => How are you?
[url] => how-are-you
)
[6] => Array
(
[cat] => Running shoes
[url] => running-shoes
)
)
)
I want to make it look like this:
Array
(
[1] => Array
(
[1] => Array
(
[cat] => Hello!
[url] => hello
)
[2] => Array
(
[cat] => Good job!
[url] => good-job
)
[2] => Array
(
[1] => Array
(
[cat] => How are you?
[url] => how-are-you
)
[2] => Array
(
[cat] => Running shoes
[url] => running-shoes
)
)
)
This solution Reset keys of array elements in php? "just" works on tow diemensional arrays, if Im not wrong.
you could write a short function to do it with array_map:
function mappingfunction($array){
$remappedarray = array();
foreach($array as $layer){
$remappedarray[] = array_map('array_values', $array);
}
return $remappedarray;
}
if you want to preserve the keys:
function mappingfunction($array){
$remappedarray = array();
foreach($array as $key => $layer){
$remappedarray[$key] = array_map('array_values', $array);
}
return $remappedarray;
}
Untested, but should point you in the right direction.