Array Multisort with a multidirectional array [duplicate] - php

This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 7 years ago.
This one is baffling me at the moment, and I'm a little confused as to what it is doing.
So I have a multi directional array:
$h_info[69993] = array('price' => '1.00', 'url' => 'url', 'rating' => '4');
$h_info[85398] = array('price' => '3.00', 'url' => 'url', 'rating' => '2');
$h_info[34394] = array('price' => '9.00', 'url' => 'url', 'rating' => '0');
Now I have the following while loop
foreach ($h_info as $row) {
foreach ($row as $key => $value){
${$key}[] = $value; //Creates $price, $url... arrays.
}
}
array_multisort($price, SORT_ASC, $h_info);
Now this works, but it removes the $h_info id from the array and outputs
Array
(
[0] => Array
(
[price] => 39
[url] => url,
[rating] => 4.5
)
...
But i need the ID to stay - when I do this:
foreach ($h_info as $row => $id) {
foreach ($row as $key => $value){
${$key}[] = $value; //Creates $price, $url... arrays.
}
}
array_multisort($price, SORT_ASC, $h_info);
The sort no longer works, but outputs the array correctly:
Array
(
[69993] => Array
(
[price] => 39
[url] => url,
[rating] => 4.5
)
...

Try this
$h_info[69993] = array('price' => '1.00', 'url' => 'url', 'rating' => '4');
$h_info[85398] = array('price' => '3.00', 'url' => 'url', 'rating' => '2');
$h_info[34394] = array('price' => '9.00', 'url' => 'url', 'rating' => '0');
//intitalize array
$result = array(); // or $result = [];
//add your main key into "key" parameter of array
array_walk($h_info, function (&$value,$key) use (&$result) {
$arr_info = $value;
$arr_info['key'] = $key;
$result[] = $arr_info;
});
//sort in ascending order by price
usort($result, function($a, $b) {
if($a['price']==$b['price']) return 0;
return $b['price'] < $a['price']?1:-1; // return $a['price'] < $b['price']?1:-1;(note : if you need it in descending order)
});
echo "<pre>";
print_r($result);
?>
and you will get result like this
Array
(
[0] => Array
(
[price] => 1.00
[url] => url
[rating] => 4
[key] => 69993
)
[1] => Array
(
[price] => 3.00
[url] => url
[rating] => 2
[key] => 85398
)
[2] => Array
(
[price] => 9.00
[url] => url
[rating] => 0
[key] => 34394
)
)
in ascending order by price
if you need to know more information abouta array_walk() and usort() please check this links :
http://php.net/manual/en/function.array-walk.php
http://php.net/manual/en/function.usort.php

Related

Grouping in array

I have following array..I am trying to group this.
Array
(
[0] => Array
(
[Title] => HoMedics MAN-300
[ean] => 31262006288
[upc] => 31262006288
[ProductImageName] =>
[CdnUri] =>
[ASIN] => B000050FEU
[ListPrice] => 129.99
[Status] => 2
[ActualPrice] => 129.99
[ProductID] => 5286728
)
)
I want to group this into
Array
(
[0] => Array
(
[VitalInfo]=>array(
[Title] => HoMedics MAN-300
[ean] => 31262006288
[upc] => 31262006288
[ProductImageName] =>
[CdnUri] =>
[ASIN] => B000050FEU
)
[Price]=>array(
[ListPrice] => 129.99
[Status] => 2
[ActualPrice] => 129.99
[ProductID] => 5286728
)
)
I tried but it doesn't happen as I want ...any help would be great...Thanx in advance..
try this,
CODE :
foreach($old_array as $key_old => $val_old)
{
foreach($val_old as $key => $val)
{
if(in_array($key, $VitalInfo_array))
{
$new_array[$key_old]['VitalInfo'][$key] = $val;
}
else
{
$new_array[$key_old]['Price'][$key] = $val;
}
}
}
OUTPUT :
Array
(
[0] => Array
(
[VitalInfo] => Array
(
[Title] => HoMedics MAN-300
[ean] => 31262006288
[upc] => 31262006288
[ProductImageName] =>
[CdnUri] =>
[ASIN] => B000050FEU
)
[Price] => Array
(
[ListPrice] => 129.99
[Status] => 2
[ActualPrice] => 129.99
[ProductID] => 5286728
)
)
)
DEMO
i hope it will be helpful.
Simply loop through your array and customize a new array accordingly.
Assuming $array is the original array, and $result is the customized array, try this:
foreach ($array as $k => $arr) {
$result[$k]['VitalInfo'] = array(
'Title' => $arr['Title'],
'ean' => $arr['ean'],
'upc' => $arr['upc'],
'ProductImageName' => $arr['ProductImageName'],
'CdnUri' => $arr['CdnUri'],
'ASIN' => $arr['ASIN']
);
$result[$k]['Price'] = array(
'ListPrice' => $arr['ListPrice'],
'Status' => $arr['Status'],
'ActualPrice' => $arr['ActualPrice'],
'ProductID' => $arr['ProductID']
);
}
Input : $info // Your Original Array
Ouput : $finalArr // Your Required Array
$vitalInfo = array ('Title','ean','upc','ProductImageName','CdnUri','ASIN');
$price = array ('ListPrice','Status','ActualPrice','ProductId');
$finalArr = array();
foreach ($info as $arr) {
$result = array();
foreach($arr as $k => $v){
if(in_array($k,$vitalInfo))
$result['VitalInfo'][$k] = $v;
else if(in_array($k,$price))
$result['Price'][$k] = $v;
}
$finalArr[] = $result;
}
If you are grouping this in php, have a look at these answers.
Or just copy this:
$input = [0 => [
'Title' => 'HoMedics MAN-300',
'ean' => 31262006288,
'upc' => 31262006288,
'ProductImageName' => '',
'CdnUri' => '',
'ASIN' => 'B000050FEU',
'ListPrice' => 129.99,
'Status' => 2,
'ActualPrice' => 129.99,
'ProductID' => 5286728
]];
foreach ($input as $in){
$out['VitalInfo'] = [];
$out['Price'] = [];
foreach ($in as $key => $i){
if (in_array($key, ['Title', 'ean', 'upc', 'ProductImageName', 'CdnUri', 'Asin'])){
$out['VitalInfo'][] = [$key => $i];
} else {
$out['Price'][] = [$key => $i];
}
}
$output[]=$out;
}
echo '<pre>';
var_dump($output);

Get sum of values which have same value for key php array

I have below array,
Array ( [0] => Array ( [report_id] => 1 [amount] => 100.00 [category_name] => Trial1 ) [1] => Array ( [report_id] => 1 [amount] => 150.00 [category_name] => Trial2 ) [2] => Array ( [report_id] => 1 [amount] => 200.00 [category_name] => Trial2 )
What i want to send to have JSON with below format
It will get some of Equal category name and then send it as json.
[{'category_name': 'Trial1', 'Sum':100]}, {'category_name':'Trial2', 'Sum':350]
How can i achieve this?
Was thinking to get foreach loop and then make compare of category_name and use .=+ to get sum? but i lost there,
Thanks,
Try below solution:
<?php
$array = array (
'0' => Array ( 'report_id' => 1, 'amount' => '100.00', 'category_name' => 'Trial1' ) ,
'1' => Array ( 'report_id' => 1, 'amount' => '150.00' ,'category_name' => 'Trial2' ),
'2' => Array ( 'report_id' => 1, 'amount' => '200.00' ,'category_name' => 'Trial2' ) ,
);
$new_array = array();
foreach($array as $a){
if(!isset($new_array[$a['category_name']]['amount'])){
$new_array[$a['category_name']]['amount'] = 0;
}
$new_array[$a['category_name']] = array(
'category_name' => $a['category_name'],
'amount' => $new_array[$a['category_name']]['amount'] + $a['amount'],
);
}
//print_r(array_values($new_array));
echo json_encode(array_values($new_array));
Output
[{"category_name":"Trial1","amount":100},{"category_name":"Trial2","amount":350}]
Possible solution:
$categoriesArray = array();
foreach ($yourArray as $arrayItem) {
if (!isset($categoriesArray[$arrayItem['category_name']])) {
$categoriesArray[$arrayItem['category_name']] = array(
'category_name' => $arrayItem['category_name'],
'sum' => 0
);
}
$categoriesArray[$arrayItem['category_name']]['sum'] += $arrayItem['amount'];
}
$categoriesArray = json_encode(array_values($categoriesArray));
Assuming $input is your array and $output is the JSON string:
$categorysum = [];
array_walk($input, function($el) use (&$categorysum) {
$categorysum += [$el['category_name'] => ['category_name' => $el['category_name'], 'Sum' => 0]];
$categorysum[$el['category_name']]['Sum'] += $el['amount'];
});
$output = json_encode(array_values($categorysum));

PHP Array Search and Delete

I have two array:
Array 1:
Array ( [0] => Array ( [id] => et1 [supplier_id] => 4 [supplier_product_code] => 00054X [is_active] => 1 )
[1] => Array ( [id] => et2 [supplier_id] => 4 [supplier_product_code] => 000558 [is_active] => 1 )
[2] => Array ( [id] => et3 [supplier_id] => 5 [supplier_product_code] => 00054X [is_active] => 1 ));
Array 2:
Array ( [0] => Array ([id] => et1 [same_sku] => et3);
I need to delete all the same_skus in array1 from array2.
So from my result array I need array1 to be:
Array ( [0] => Array ( [id] => et1 [supplier_id] => 4 [supplier_product_code] => 00054X [is_active] => 1 )
[1] => Array ( [id] => et2 [supplier_id] => 4 [supplier_product_code] => 000558 [is_active] => 1 ));
Code that I have right now does not work.
public function search_array($array, $val)
{
foreach ($array as $key => $row)
{
if ($row['id'] === $val)
{
return $key;
}
}
}
foreach($array2->result() as $row)
{
$id = $row->id;
$same_sku = $row->same_sku;
$key = $this->search_array($array1, $id);
if(!empty($key))
{
$same_sku_key = $this->search_array($array1, $same_sku);
if(!empty($same_sku_key))
unset($array1[$same_sku_key]);
}
}
In the following code I have recreated the two arrays from your example. I then created a function that removes from a haystack array (array1) all of the sub arrays that have an "id" that matches the value of "same_sku" within a needle array (array2). The final line echos the result array.
EDIT
I have modified the original answer to pass the array values by reference and unset the unwanted sub arrays, instead of passing by value, looping, and returning another array. This should resolve the memory issue, as well as the other issue mentioned in your comment.
$array1 = array(
array(
'id' => 'et1',
'supplier_id' => '4',
'supplier_product_code' => '00054X',
'is_active' => '1'
),
array(
'id' => 'et2',
'supplier_id' => '4',
'supplier_product_code' => '000558',
'is_active' => '1'
),
array(
'id' => 'et3',
'supplier_id' => '5',
'supplier_product_code' => '00054X',
'is_active' => '1'
),
array(
'id' => 'et4',
'supplier_id' => '5',
'supplier_product_code' => '00054X',
'is_active' => '1'
)
);
$array2 = array(
array(
'id' => 'et1',
'same_sku' => 'et3'
),
array(
'id' => 'et2',
'same_sku' => 'et4'
)
);
function remove_same_sku(&$haystack, &$needles){
foreach($needles as $needle){
foreach($haystack as $key => $val){
if($val['id'] === $needle['same_sku']){
unset($haystack[$key]);
}
}
}
}
remove_same_sku($array1, $array2);
echo print_r($array1);

Rearrange array

I am getting this array when form is submitted
array
'item' =>
array
0 => string 'Salt'
1 => string 'Pepper'
'quantity' =>
array (size=2)
0 => string '2 spoon'
1 => string '5'
and now want to rearrange above array, so it should look like
array
'0' =>
array
'item' => string 'Salt'
'quantity' => string '2 spoon'
'1' =>
array
'item' => string 'Pepper'
'quantity' => string '5'
I tried so many combinations but failed, will somebody help me how to rearrange this array. Any help will be more than appreciated.
Try this
$array = array(
'item' =>
array(
0 => 'Salt',
1 => 'Pepper'),
'quantity' =>
array(
0 => '2 spoon',
1 => '5')
);
$new_array = array();
foreach ($array['item'] as $key => $value) {
$new_array[$key]["item"] = $value;
$new_array[$key]["quantity"] = $array['quantity'][$key];
}
echo "<pre>";
var_dump($new_array);
Do it as below -
<?php
$arr=array(
'item' =>
array(
0 => 'Salt' ,
1 => 'Pepper'
),
'quantity' =>
array (
0 =>'spoon',
1 =>'5'
)
);
$result=array();
$com=array_combine($arr['item'],$arr['quantity']);
foreach($com as $k=>$v)
{
$result[]=array("item"=>$k,"quantity"=>$v);
}
print_r($result);
?>
OUTPUT
Array (
[0] => Array ( [item] => Salt [quantity] => spoon )
[1] => Array ( [item] => Pepper [quantity] => 5 )
)
try this, I think this would help you,
$a = array(
'item' =>
array(
0 => 'Salt',
1 => 'Pepper'),
'quantity' =>
array(
0 => '2 spoon',
1 => '5')
);
$i = 0;
foreach($a['item'] as $row){
$b[$i]["item"] = $row;
$b[$i]["quantity"] = $a['quantity'][$i];
$i++;
}
print_r($b);
Output from print_r() will be
Array
(
[0] => Array
(
[item] => Salt
[quantity] => 2 spoon
)
[1] => Array
(
[item] => Pepper
[quantity] => 5
)
)
You can simply use array_walk like as
$result = [];
array_walk($arr['item'], function($v, $k)use(&$result, $arr) {
$result[$k]['item'] = $arr['item'][$k];
$result[$k]['quantity'] = $arr['quantity'][$k];
});
print_r($result);
Demo
Hoping that your array is stored in the $array variable and that item is leading. Meaning that there is always an item in the array and not always a quantity
<?php
foreach($array['item'] as $key => $item) {
$newArray[$key]['item'] = $item;
if (isset($array['quantity'][$key]) {
$newArray[$key]['quantity'] = $array['quantity'][$key];
} else {
$newArray[$key]['quantity'] = 0;
}
?>

Merge an array with specified values into one key

Right now, I have array sets like these:
[9] => Array
(
[sl] => 10
[upload_dt] => 2015-04-15 14:39:58
[total_files] => 3
[file_name] => logo01.png
[remarks] => qqq
[status] => pending
[download_file] => http://localhost/web/download_file21
)
[10] => Array
(
[sl] => 10
[upload_dt] => 2015-04-15 14:39:58
[total_files] => 3
[file_name] => face.jpg
[remarks] => 5645645
[status] => pending
[download_file] => http://localhost/web/download_file22
)
[11] => Array
(
[sl] => 10
[upload_dt] => 2015-04-15 14:39:58
[total_files] => 3
[file_name] => ID_11401871809904(15).pdf
[remarks] => 567567
[status] => pending
[download_file] => http://localhost/web/download_file23
)
Now, I need to merge same values in some of the indices into one arrays.
The merged array values should look like this in the end.
[9] => Array
(
[sl] => 10
[upload_dt] => 2015-04-15 14:39:58
[total_files] => 3
[file_name] => logo01.png , face.jpg, ID_11401871809904(15).pdf
[remarks] => qqq, 5645645 , 567567
[status] => pending, pending ,pending
[download_file] => http://localhost/web/download_file21,
http://localhost/web/download_file22,
http://localhost/web/download_file23
)
Now, I tried using array_merge but it didn't actually work in this case.
Solution will be like this:
<?php
$result = array();
$ar1[9] = Array
(
'sl' => 10,
'upload_dt' => '2015-04-15 14:39:58',
'total_files' => 3,
'file_name' => 'logo01.png',
'remarks' => 'qqq',
'status' => 'pending',
'download_file' => 'http://localhost/web/download_file21'
);
$ar1[10] = Array
(
'sl' => 10,
'upload_dt' => '2015-04-15 14:39:58',
'total_files' => 3,
'file_name' => 'face.jpg',
'remarks' => '5645645',
'status' => 'pending',
'download_file' => 'http://localhost/web/download_file22'
);
$ar1[11] = Array
(
'sl' => 10,
'upload_dt' => '2015-04-15 14:39:58',
'total_files' => 3,
'file_name' => 'ID_11401871809904(15).pdf',
'remarks' => 567567,
'status' => 'pending',
'download_file' => 'http://localhost/web/download_file23'
);
foreach($ar1 as $record){
$keys = array_keys($record);
foreach($keys as $key) {
if(array_key_exists($key,$result)){
$valeInKey = explode(',', $result[$key]);
if (!in_array($record[$key], $valeInKey)){
$result[$key]= $result[$key] .",".$record[$key];
}
} else{
$result[$key]= $record[$key];
}
}
}
echo"<pre>";print_r($result);exit;
?>
You're actually merging strings inside those arrays so just ditch the array_merge idea, and just use a simple loop then use the key as your basis to concatenate strings. Rough example:
$result = array();
foreach($array as $values) {
if(!isset($result[$values['sl']])) {
$result[$values['sl']] = $values; // initial
} else {
foreach(array('file_name', 'remarks', 'status', 'download_file') as $field) {
$result[$values['sl']][$field] .= ", {$values[$field]}";
}
}
}
Sample Output
array_merge won't work, because the keys would overwrite each other.
A solution would be to merge them with a the help of a foreach. Something like this:
$new = array();
foreach($arr as $key => $value) {
$new[$key] .= ", ".$value;
}
But you would have multiple entries for every single array you want to merge. If you just want to have them for a few, you have to check the key and do something accordingly.

Categories