PHP Retrieve minimum values in a 2D associative array [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have the below array:
Array
(
[0] => Array
(
[id] => 1
[price1] => 16
[price2] => 10
[price3] => 3
)
[1] => Array
(
[id] => 2
[price1] => 19
[price2] => 2
[price3] => 6
)
[2] => Array
(
[id] => 3
[price1] => 14
[price2] => 32
[price3] => 1
)
)
I want to get the lower price from each row independent from the other rows. for example for id=1 the lower price is 3 and for id=2 the lower is 2 and so on. Any idea how to automate this.

Possible solution:
Demo
foreach($array as $item)
{
$lowestKey = '';
foreach($item as $key => $value)
{
if(strpos($key, 'price') === 0)
{
if($lowestKey == '')
{
$lowestKey = $key;
}
else
{
if($value < $item[$lowestKey])
{
$lowestKey = $key;
}
}
}
}
echo 'lowest for id ' . $item['id'] . ': ' . $item[$lowestKey];
}
The benefits of this method are:
The price keys don't have to be consecutive, or even numerical. Any key that begins with price is treated as a price.
There can be unlimited prices, it's not restricted to three.
Any other data stored in the array won't affect it or break anything. So for example if in future you added a description key, it won't affect the code or require any modifications.

Try this:
$newarray = array();
foreach ($array as $row)
{
$id = $row['id'];
unset($row['id']);
$newarray[$id] = min($row);
}
There you go. $newarray now contains the id => {lowest value} of each row.

$r = array_reduce($array, function(&$result, $item) {
$key = $item['id'];
unset($item['id']);
$result[$key] = min($item);
return $result;
});

Try the below:
$prices = array(0 => array ( 'id' => 1,
'price1' => 16,
'price2' => 10,
'price3' => 3
),
1 => array ( 'id' => 2,
'price1' => 19,
'price2' => 2,
'price3' => 6
),
2 => array ( 'id' => 3,
'price1' => 14,
'price2' => 32,
'price3' => 1
)
);
foreach($prices as $price) {
$tmp_arr = array(0=> $price['price1'], 1=> $price['price2'], 2=> $price['price3']);
sort($tmp_arr);
$arr_low_price = array('id'=> $price['id'], 'low_price' => $tmp_arr[0]);
print_r($arr_low_price);
echo '<br />';
}

Try may help:
$price = array();
foreach( $array as $key=>$each ){
$low = $each['price1'];
if( $each['price2'] < $low ){
$low = $each['price2'];
}
if( $each['price3'] < $low ){
$low = $each['price3'];
}
$price[$key] = $low;
}
print_r( $price );

Related

I want to add frequency on base of position of ranking which their execution partially run not accurate - PHP

I have conditional function which their execution not running as per business meet which to be require transformation as with desired result. This function contain ranking and frequency which are part of multidimensional array and their execution of sum on based of some calculation
I want to add frequency on base of position of ranking which their execution partially run not accurate. could you please help me out.
<?php
$arr = array (
'AMXB 5321' => array(
array("course_title_code" => "AMB 5321",
"content" => "Course",
"total" => "303",
"count" => "85",
"ranking" => array(array(5),array(2,4,5)),
"frequency" => array(array(5),array(1,2,11))),
array("course_title_code" => "AMB 5321",
"content" => "Succeed in the course",
"total" => "300",
"count" => "85",
"ranking" => array(array(3,5),array(3,4,5)),
"frequency" => array(array(1,4),array(1,2,11))
)
));
array_walk($arr, function(&$v,$k){
foreach($v as $key => &$s){
$s['ranking'] = implode(',',range(1,5));
foreach($s['frequency'] as $key => &$value){
$temp = $value;
$value = (count($value) == 5) ? $value : array_merge(array_fill(0, 5 - count($value), 0), $temp);
if($key == 1){
for($i=0;$i<count($value);$i++){
$value[$i] += $s['frequency'][$key-1][$i];
}
$temFormat = implode(',',$s['frequency'][1]);
}
}
unset($s['frequency']);
$s['frequency'] = $temFormat;
}
});
echo "<pre>";
print_r($arr);
?>
Desired Result
Array
(
[AMXB 5321] => Array
(
[0] => Array
(
[course_title_code] => AMB 5321
[content] => Course
[total] => 303
[count] => 85
[ranking] => 1,2,3,4,5
[frequency] => 0,1,0,2,16
)
[1] => Array
(
[course_title_code] => AMB 5321
[content] => Succeed in the course
[total] => 300
[count] => 85
[ranking] => 1,2,3,4,5
[frequency] => 0,0,2,2,15
)
)
)
You can do that like this:
function calRanking($ranks, $freqs) {
$res = array_fill(0, 5, 0); // create array of 0
foreach($ranks as $k => $v) {
foreach(array_map(null, $v, $freqs[$k]) as $e) {
$res[$e[0]-1]+= $e[1]; //add the frequency according to rank key
}
}
return $res;
}
foreach($a as &$v) { // for each calculate and implode
$v["frequency"] = implode(',', calRanking($v["ranking"], $v["frequency"]));
$v["ranking"] = implode(',',range(1,5));
}
I assumed user with a lot of answer and reputation may build the question in more suite-able way for future learning...
Live example: 3v4l
Reference: array-fill, array-map

How to remove the duplicate data into array [duplicate]

This question already has answers here:
Filter/Remove rows where column value is found more than once in a multidimensional array
(4 answers)
Closed 9 months ago.
Need help for the code.
Here is my list of array which i want to remove the two (2) Wi-fi.
Array
(
[20-10] => Array
(
[facilityCode] => 20
[facilityGroupCode] => 10
[order] => 1
[number] => 1968
[voucher] =>
[description] => Year of construction
)
[550-70] => Array
(
[facilityCode] => 550
[facilityGroupCode] => 70
[order] => 1
[indFee] =>
[indYesOrNo] => 1
[voucher] =>
[description] => Wi-fi
)
[20-60] => Array
(
[facilityCode] => 20
[facilityGroupCode] => 60
[order] => 1
[indLogic] => 1
[voucher] =>
[description] => Shower
)
[261-60] => Array
(
[facilityCode] => 261
[facilityGroupCode] => 60
[order] => 1
[indFee] =>
[indYesOrNo] => 1
[voucher] =>
[description] => Wi-fi
)
)
I do also tried the array_unique();
here is the result:
Array
(
[0] => Year of construction
[1] => Shower
[2] => Wi-fi
)
But i want to keep the facilityCode,facilityGroupCode,order,number etc.
Thanks for any help.
One liner is all can do your requirement,
$result = array_reverse(array_values(array_column(array_reverse($arr), null, 'description')));
Source link for your requirement.
//populate data
$mainArr = array();
$first = array(
"facilityCode" => 20,
"facilityGroupCode" => 10,
"order" => 1,
"number" => 1968,
"voucher" => "",
"description" => "Year of construction",
);
$second = array(
"facilityCode" => 550,
"facilityGroupCode" => 70,
"order" => 1,
"indFee" => "",
"indYesOrNo" => 1,
"voucher" => "",
"description" => "Wi-fi"
);
$mainArr["20-10"] = $first;
$mainArr["550-70"] = $second;
$mainArr["261-60"] = $second;
//get duplicates
$counter = 0;
$duplicates = array();
foreach ($mainArr as $key=>$val) {
$counter++;
if (in_array($key, $duplicates)) continue;
$i = 0;
foreach ($mainArr as $key1=>$val1) {
if ($i < $counter) {
$i++;
continue;
}
if ($val["description"] == $val1["description"]) {
array_push($duplicates, $key1);
}
}
}
//remove duplicates
foreach($duplicates as $key) {
unset($mainArr[$key]);
}
$itemRows = array(); // Your main array
$descriptionValues = array();
foreach ($itemRows as $itemKey => $itemRow) {
foreach ($itemRow as $key => $value) {
if ($key == 'description') {
if (in_array($value, $descriptionValues)) {
unset($itemRows[$itemKey]);
continue 2;
}
$descriptionValues[] = $value;
}
}
}

PHP - Convert a Single Array into a Multidimensional Array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm newbie in PHP.
I need send data for API purpose.
I have array print_r($detail) like this
Array
(
[0] => Array
(
[id] => item1
)
[1] => Array
(
[price] => 300
)
[2] => Array
(
[quantity] => 1
)
[3] => Array
(
[id] => item2
)
[4] => Array
(
[price] => 400
)
[5] => Array
(
[quantity] => 2
)
)
And I want convert it to multidimensional before sending to another process, like
Array
(
[0] => Array
(
[id] => item1
[price] => 300
[quantity] => 1
)
[1] => Array
(
[id] => item2
[price] => 400
[quantity] => 2
)
)
How it is possible?
You can split your $details array into multiple chunks. I've written the following function which accepts a custom chunk size (note count($initialArray) % $chunkSize === 0 must be true):
function transformArray(array $initialArray, $chunkSize = 3) {
if (count($initialArray) % $chunkSize != 0) {
throw new \Exception('The length of $initialArray must be divisible by ' . $chunkSize);
}
$chunks = array_chunk($initialArray, 3);
$result = [];
foreach ($chunks as $chunk) {
$newItem = [];
foreach ($chunk as $item) {
$newItem[array_keys($item)[0]] = reset($item);
}
$result[] = $newItem;
}
return $result;
}
Given your details array, calling transformArray($details) will result in:
The customizable chunk size allows you to add more data to your source array:
$details = [
['id' => 'item1'],
['price' => 300],
['quantity' => 1],
['anotherProp' => 'some value'],
['id' => 'item2'],
['price' => 400],
['quantity' => 2],
['anotherProp' => 'another value'],
];
The function call is now transformArray($details, 4);:
This version may be with the same result of #PHPglue answer. But this takes only one foreach. I think this is faster, more efficient way as stated here by one of the Top SO Users.
Try to look if you want it.
Live Demo
<?php
function explodeArray($arr)
{
$newArr = array();
foreach($arr as $row)
{
$key = array_keys($row)[0];
$curArr = count($newArr) > 0 ? $newArr[count($newArr)-1] : array();
if( array_key_exists($key, $curArr) )
{
array_push($newArr, array($key=>$row[$key]) );
}
else
{
$index = count($newArr) > 0 ? count($newArr) - 1 : 0 ;
$newArr[$index][$key] = $row[$key];
}
}
return $newArr;
}
Different Arrays for testing.
$detail = array(
array('id'=>'item1'),
array('price'=>300),
array('quantity'=>1),
array('id'=>'item2'),
array('price'=>400),
array('quantity'=>2)
);
var_dump( explodeArray($detail) );
$detail_match = array(
array('id'=>'item1'),
array('price'=>300),
array('quantity'=>1),
array('newkey'=>'sample'),
array('id'=>'item2'),
array('price'=>400),
array('quantity'=>2),
array('newkey'=>'sample')
);
var_dump( explodeArray($detail_match) ); // Works with any size of keys.
$detail_diff_key = array(
array('id'=>'item1'),
array('price'=>300),
array('quantity'=>1),
array('diff1'=>'sample1'),
array('id'=>'item2'),
array('price'=>400),
array('quantity'=>2),
array('diff2'=>'sample2')
);
var_dump( explodeArray($detail_diff_key) ); // Works with any size of keys and different keys.
$detail_unmatch = array(
array('id'=>'item1'),
array('price'=>300),
array('quantity'=>1),
array('unmatchnum'=>'sample1'),
array('id'=>'item2'),
array('price'=>400),
array('quantity'=>2)
);
var_dump( explodeArray($detail_unmatch) );
I think this little block of code work for you.
Use:
$detail = array(
"0" => array("id" => "item1"),
"1" => array("price" => "300"),
"2" => array("quantity" => "1"),
"3" => array("id" => "item2"),
"4" => array("price" => "400"),
"5" => array("quantity" => "2"),
"6" => array("id" => "item3"),
"7" => array("price" => "500"),
"8" => array("quantity" => "3")
);
$i = 0;
$j = 0;
$multi_details = array();
while($j < count($detail)){
$multi_details[$i][id] = $detail[$j++][id];
$multi_details[$i][price] = $detail[$j++][price];
$multi_details[$i][quantity] = $detail[$j++][quantity];
$i++;
}
echo '<pre>';
print_r($multi_details);
echo '</pre>';
Output:
Array
(
[0] => Array
(
[id] => item1
[price] => 300
[quantity] => 1
)
[1] => Array
(
[id] => item2
[price] => 400
[quantity] => 2
)
[2] => Array
(
[id] => item3
[price] => 500
[quantity] => 3
)
)
Something like this should do it
$newArray = array();
$newRow = array();
foreach ($array as $row) {
$key = array_keys($row)[0];
$value = array_values($row)[0];
if ($key == 'id') {
$newArray[] = $newRow;
}
$newRow[$key] = $value;
}
$newArray[] = $newRow;
This version looks for repeat keys then creates a new Array whenever they are the same so you could have some different data. Hope it helps.
function customMulti($customArray){
$a = array(); $n = -1; $d;
foreach($customArray as $i => $c){
foreach($c as $k => $v){
if(!isset($d)){
$d = $k;
}
if($k === $d){
$a[++$n] = array();
}
$a[$n][$k] = $v;
}
}
return $a;
}
$wow = customMulti(array(array('id'=>'item1'),array('price'=>300),array('quantity'=>1),array('id'=>'item2'),array('price'=>400),array('quantity'=>2)));
print_r($wow);

Merge duplicates in array PHP [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I have an array generated daily that will have duplicate products in it.
[0] => Array
(
[product_id] => 85
[name] => Widescreen Espresso v6.1
[quantity] => 1
)
[1] => Array
(
[product_id] => 85
[name] => Widescreen Espresso v6.1
[quantity] => 2
)
[2] => Array
(
[product_id] => 114
[name] => Panama Esmerelda Diamond Mountain
[quantity] => 1
)
I want to find duplicate products and total them up in an array that would look like this:
[0] => Array
(
[product_id] => 85
[name] => Widescreen Espresso v6.1
[quantity] => 3
)
[1] => Array
(
[product_id] => 114
[name] => Panama Esmerelda Diamond Mountain
[quantity] => 1
)
UPDATE:
I didn't want to remove the duplicates I want to merge duplicates so that the quantity of the product is added together. I managed to work a solution to it with the help of Meenesh Jain's answer below.
$final_array = array();
foreach($order_data as $item => $item_value) {
$pid = $item_value['product_id'];
if(!isset($final_array[$pid])) {
$final_array[$pid] = $item_value;
} else {
$final_array[$pid]['quantity'] += $item_value['quantity'];
}
}
print_r(array_values($final_array));
You can do it with mysqli
OR
you can apply a custom method on your array
$temp_array = $new_array = array();
foreach($array as $key => $arr_values){
if(!in_array($arr_values['product_id'], $temp_array)){
array_push($temp_array, $arr_values['product_id']);
array_push($new_array,$array[$key]);
}
}
// this code will do the trick
My try:
function newArray($oldarray){
$newarray;
$newarray[0] = $oldarray[0];
$ids;
$ids[0] = array($oldarray[0][product_id],0);
for($i = 1; $i < count($oldarray);$i++){
$add = true;
for($x = 0; $x < count($ids);$x++){
if($oldarray[$i][product_id] == $ids[$x][0]){
$add = false;
$newarray[$ids[$x][1]-1] = array($newarray[$ids[$x][1]-1][product_id],$newarray[$ids[$x][1]-1][name],$newarray[$ids[$x][1]-1][quantity]+$oldarray[$i][quantity]);
}
}
if($add == true){
$newarray[count($newarray)] = $oldarray[$i];
$ids[count($ids)] = array($oldarray[$i][product_id],count($newarray));
}
}
return $newarray;
}
You need to use this function (need to pass $array=name of array and $key as 'product_id'):
function super_unique($array,$key)
{
$temp_array = array();
foreach ($array as &$v) {
if (!isset($temp_array[$v[$key]]))
$temp_array[$v[$key]] =& $v;
}
$array = array_values($temp_array);
return $array;
}
Example :
<?php
$vikas=array('0' => array
(
'product_id' => 85,
'name' => "Widescreen Espresso v6.1",
'quantity' => 1
),
'1' => array
(
'product_id' => 85,
'name' => "Widescreen Espresso v6.1",
'quantity' => 2
),
'2' => array
(
'product_id' => 114,
'name' => "Panama Esmerelda Diamond Mountain",
"quantity" => 1
)
);
function super_unique($array,$key)
{
$temp_array = array();
foreach ($array as &$v) {
if (!isset($temp_array[$v[$key]]))
$temp_array[$v[$key]] =& $v;
}
$array = array_values($temp_array);
return $array;
}
//print_r(array_unique($vikas['product_id']));
$vik=super_unique($vikas,'product_id');
print_r($vik);
?>

How to sum same array in php [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to sum array in same key and different value.
Array
(
0 => Array
(
'locker_id' => 3,
'locker_model' => 1,
'qty' => 2
),
1 => Array
(
'locker_id' => 3,
'locker_model' => 1,
'qty' => 1
),
2 => Array
(
'locker_id' => 2,
'locker_model' => 1,
'qty' => 2
),
3 => Array
(
'locker_id' => 3,
'locker_model' => 1,
'qty' => 2
),
4 => Array
(
'locker_id' => 2,
'locker_model' => 1,
'qty' => 2
)
);
I want Output it
Array
(
0 => Array
(
'locker_id' => 3,
'locker_model' => 1,
'qty' => 5
),
1 => Array
(
'locker_id' => 2,
'locker_model' => 1,
'qty' => 4
)
);
Thanks.
You could browse your array while creating a new one with keys like "locker_id-locker_model", then you can easily check if your locker exists in this array with array_key_exists function.
$inputArray = array( ... ); // this is your message array
$outputArray = array();
foreach( $inputArray as $locker )
{
if( !array_key_exists( $locker["locker_id"]."-".$locker["locker_model"], $outputArray ) )
{
$outputArray[ $locker["locker_id"]."-".$locker["locker_model"] ] = array(
"locker_id" => $locker["locker_id"],
"locker_model" => $locker["locker_model"],
"qty" => 0
);
}
$outputArray[ $locker["locker_id"]."-".$locker["locker_model"] ]["qty"]++;
}
var_dump( $outputArray );
$dataArr = array
(
0 => array
(
'locker_id' => 3,
'locker_model' => 1,
'qty' => 2
),
1 => array
(
'locker_id' => 3,
'locker_model' => 1,
'qty' => 1
),
2 => array
(
'locker_id' => 2,
'locker_model' => 1,
'qty' => 2
),
3 => array
(
'locker_id' => 3,
'locker_model' => 1,
'qty' => 2
),
4 => array
(
'locker_id' => 2,
'locker_model' => 1,
'qty' => 2
)
);
$sumArr = array();
if(count($dataArr)>0){
foreach($dataArr as $data){
if(!isset($sumArr[$data['locker_id']])){
$sumArr[$data['locker_id']] = $data;
}
$sumArr[$data['locker_id']]['qty'] +=$data['qty'];
}
}
echo "<pre>";print_r($sumArr);
Considering $array1 is your first array,
$array2 = array();
foreach($array1 as $k=>$v) {
if(!isset($array2[$v['locker_id']])) {
$array2[$v['locker_id']] = $v;
} else {
$array2[$v['locker_id']]['qty'] += $v['qty'];
}
}
print_r($array2);
Try this
$arr is your array
$j = 0;
$new = array();
$new[0][qty];
for($i=0;$i<arraylength;$i++){
foreach($arr as $key => $value) {
if($arr[$i][lockerid] == $arr[$key][lockerid]) {
$new[$j][lockerid] = $arr[$key][lockerid];
$new[$j][lockermodel] = $arr[$key][lockermodel];
$new[$j][qty] = $new[$i][qty] + $arr[$key][qty];
J++;
}
}
}
$result = array();
foreach($array as $key => $value){
if(isset($value['locker_id'])){
$result[$value['locker_id']]['qty'] += $value['qty'];
}
else{
$result[$value['locker_id']] = $value;
}
}
You have to loop over your array and save it to another let's say $result. In $result you should put the locker_id as key and then you only have to verify if that key exists. If it is you add the qty value, if isn't you have to add the entire new item.
try this
$ARR_OUTPUT = array();
// $arr will contains your input array
foreach($arr as $arr_val)
{
$locker_id = $arr_val['locker_id'];
$locker_model = $arr_val['locker_id'];
$qty = $arr_val['locker_id'];
if(isset($ARR_OUTPUT[$locker_id][$locker_model]))
{
$ARR_OUTPUT[$locker_id][$locker_model] += $qty;
}
else
{
$ARR_OUTPUT[$locker_id][$locker_model] = $qty;
}
}
echo "<pre>";
print_r($ARR_OUTPUT);
$ARR_OUTPUT2 = array();
foreach($ARR_OUTPUT as $locker_id=>$arr_values)
{
foreach($arr_values as $locker_model=>$qty)
{
$arr_temp['locker_id'] = $locker_id;
$arr_temp['locker_model'] = $locker_model;
$arr_temp['qty'] = $qty;
$ARR_OUTPUT2[] = $arr_temp;
}
}
echo "<pre>";
print_r($ARR_OUTPUT2);

Categories