Multidimensional Array delete duplicated key values with condition - php

I have an Array Like this:
$ratesData = [
1 => [
'id' => 1,
'amount' => 2
],
0 => [
'id' => 1,
'amount' => 1
],
2 => [
'id' => 1,
'amount' => 3
],
3 => [
'id' => 2,
'amount' => 2
]
];
I want to keep the duplicated id arrays with cheapest amount, the result will be like this:
[
0 => [
'id' => 1,
'amount' => 1
],
1 => [
'id' => 2,
'amount' => 2
]
]
I have a code that works with this problem, but I'm searching an elegant way to accomplish this without all this loops:
foreach($ratesData as $firstLoopKey => $firstLoopValue) {
foreach($ratesData as $secondLoopKey => $secondLoopValue) {
if($firstLoopValue['id'] === $secondLoopValue['id'] && $firstLoopKey != $secondLoopKey ) {
if ($ratesData[$secondLoopKey]['total_amount'] > $ratesData[$firstLoopKey]['total_amount']) {
$deleteElements[] = $secondLoopKey;
}
}
}
}
if (isset($deleteElements)) {
foreach ($deleteElements as $element) {
unset($ratesData[$element]);
}
}
$ratesData = array_values($ratesData);
return $ratesData;

You can sort by amount descending and then extract the array indexing by id which will eliminate the duplicates with the lowest amount overwriting the higher:
array_multisort(array_column($ratesData, 'amount'), SORT_DESC, $ratesData);
$ratesData = array_column($ratesData, null, 'id');
Yields:
Array
(
[1] => Array
(
[id] => 1
[amount] => 1
)
[2] => Array
(
[id] => 2
[amount] => 2
)
)
I always like having the key the same as a unique id to make array access/sorting easier, but you can re-index if needed:
$ratesData = array_values($ratesData);

Some simple solution:
// your source array
$ratesData = [];
// result array
$filtered = [];
foreach ($ratesData as $v) {
$id = $v['id'];
// if this is `$id`, which is not in `$filtered` yet
// or value of `$filtered[$id]['amount']` is greater then current `$v`
// then replace `$filtered[$id]` with current `$v`
if (!isset($filtered[$id]) || $filtered[$id]['amount'] > $v['amount']) {
$filtered[$id] = $v;
}
}
echo'<pre>',print_r(array_values($filtered)),'</pre>';

Another good solution
$uniqueRates = [];
foreach ($ratesData as $rateData) {
$key = $rateData['id'];
if (!\array_key_exists($key, $uniqueRates) ||
$rateData['total_amount'] < $uniqueRates[$key]['total_amount']
) {
$uniqueRates[$key] = $rateData;
}
}
return array_values($uniqueRates);

Related

Merge arrays in multidimensional array based on multiple values

[
0 => [
'qty' => 10
'section' => 'VK7B'
'time_window' => 1
]
1 => [
'qty' => 1
'section' => 'STIC'
'time_window' => 1
]
2 => [
'qty' => 1
'section' => 'STIC'
'time_window' => 1
]
]
I have this multidimensional array where I want to merge the array's if both the section and the time_window are the same, summing the qty for that array. What is an elegant way to do this?
I have tried this ($sections being the multidimensional arry), but this changes the keys and only checks for one value:
$new = []
foreach ($sections as $s) {
if (isset($new[$s['section']])) {
$new[$s['section']]['qty'] += $s['qty'];
$new[$s['section']]['time_window'] = $s['time_window'];
} else {
$new[$s['section']] = $s;
}
}
[
'VK7B' => [
'qty' => 10
'section' => 'VK7B'
'time_window' => 1
]
'STIC' => [
'qty' => 2
'section' => 'STIC'
'time_window' => 1
]
]
As pointed by #RiggsFolly in the comment you are not checking time_window are the same.
You can do it with this code:
$new = []
foreach ($sections as $s) {
// you need to save both values (section and time_window) to check both of them
if (isset($new[$s['section'].$s['time_window']])) {
$new[$s['section'].$s['time_window']]['qty'] += $s['qty'];
$new[$s['section'].$s['time_window']]['time_window'] = $s['time_window'];
} else {
$new[$s['section'].$s['time_window']] = $s;
}
}
// Now $new is an associative array => let's transform it in a normal array
$new = array_values($new);

Loop an array and retain only elements that relate to a specific key with a qualifying value

I have this array :
(
[id] => block_5df755210d30a
[name] => acf/floorplans
[data] => Array
(
[floorplans_0_valid_for_export] => 0
[floorplans_0_title] => title 1
[floorplans_0_house_area] => 40m²
[floorplans_0_bedrooms] => 1
[floorplans_1_valid_for_export] => 1
[floorplans_1_title] => title xx
[floorplans_1_house_area] => 90m²
[floorplans_1_bedrooms] => 2
[floorplans_2_valid_for_export] => 1
[floorplans_2_title] => title 2
[floorplans_2_house_area] => 50m²
[floorplans_2_bedrooms] => 1
[floorplans] => 3
)
)
As we can see in the data, we have fields (floorplans_X_valid_for_export).
What I want to do is to get the data only when this field equal to 1.
So from the given example, I want to keep only these fields:
[floorplans_1_valid_for_export] => 1
[floorplans_1_title] => title xx
[floorplans_1_house_area] => 90m²
[floorplans_1_bedrooms] => 2
[floorplans_2_valid_for_export] => 1
[floorplans_2_title] => title 2
[floorplans_2_house_area] => 50m²
[floorplans_2_bedrooms] => 1
This is an odd schema, but it can be done by iterating through the array and searching for keys where "valid_for_export" equals 1, and then using another array of field "stubs" to get the associated items by a unique identifier of X in floorplans_X_valid_for_export
$array = [
'floorplans_0_valid_for_export' => 0,
'floorplans_0_title' => 'title 1',
'floorplans_0_house_area' => '40m²',
'floorplans_0_bedrooms' => 1,
'floorplans_1_valid_for_export' => 1,
'floorplans_1_title' => 'title xx',
'floorplans_1_house_area' => '90m²',
'floorplans_1_bedrooms' => '2',
'floorplans_2_valid_for_export' => 1,
'floorplans_2_title' => 'title 2',
'floorplans_2_house_area' => '50m²',
'floorplans_2_bedrooms' => 1,
'floorplans' => 3
];
$stubs = [
'floorplans_%s_valid_for_export',
'floorplans_%s_title',
'floorplans_%s_house_area',
'floorplans_%s_bedrooms'
];
$newArr = [];
foreach ($array as $key => $value) {
if (strpos($key, 'valid_for_export') && $array[$key] == 1) {
$intVal = filter_var($key, FILTER_SANITIZE_NUMBER_INT);
foreach ($stubs as $stub) {
$search = sprintf($stub, $intVal);
if (isset($array[$search])) {
$newArr[$search] = $array[$search];
} else {
// key can't be found, generate one with null
$newArr[$search] = null;
}
}
}
}
echo '<pre>';
print_r($newArr);
Working: http://sandbox.onlinephpfunctions.com/code/23a225e3cefa2dc9cc97f53f1cbae0ea291672c0
Use a parent loop to check that the number-specific valid_for_export value is non-empty -- since it is either 0 or non-zero.
If so, then just push all of the associated elements into the result array.
Some reasons that this answer is superior to the #Alex's answer are:
Alex's parent loop makes 13 iterations (and the same number of strpos() calls); mine makes just 3 (and only 3 calls of empty()).
$array[$key] is more simply written as $value.
Sanitizing the $key to extract the index/counter is more overhead than necessary as demonstrated in my answer.
Code (Demo)
$array = [
'floorplans_0_valid_for_export' => 0,
'floorplans_0_title' => 'title 1',
'floorplans_0_house_area' => '40m²',
'floorplans_0_bedrooms' => 1,
'floorplans_1_valid_for_export' => 1,
'floorplans_1_title' => 'title xx',
'floorplans_1_house_area' => '90m²',
'floorplans_1_bedrooms' => '2',
'floorplans_2_valid_for_export' => 1,
'floorplans_2_title' => 'title 2',
'floorplans_2_house_area' => '50m²',
'floorplans_2_bedrooms' => 1,
'floorplans' => 3
];
$labels = ['valid_for_export', 'title', 'house_area', 'bedrooms'];
$result = [];
for ($i = 0; $i < $array['floorplans']; ++$i) {
if (!empty($array['floorplans_' . $i . '_valid_for_export'])) {
foreach ($labels as $label) {
$key = sprintf('floorplans_%s_%s', $i, $label);
$result[$key] = $array[$key];
}
}
}
var_export($result);
Output:
array (
'floorplans_1_valid_for_export' => 1,
'floorplans_1_title' => 'title xx',
'floorplans_1_house_area' => '90m²',
'floorplans_1_bedrooms' => '2',
'floorplans_2_valid_for_export' => 1,
'floorplans_2_title' => 'title 2',
'floorplans_2_house_area' => '50m²',
'floorplans_2_bedrooms' => 1,
)
With that constructed data it might be hard (not impossble tho), hovewer i would suggest to change it to multidimensional arrays so you have something like:
[floorplans][0][valid_for_export] => 0
[floorplans][0][title] => title 1
[floorplans][0][house_area] => 40m²
[floorplans][0][bedrooms] => 1
[floorplans][1][valid_for_export] => 1
[floorplans][1][title] => title xx
[floorplans][1][house_area] => 90m²
Rought sollution
It is not the best approach, but it should work if you dont need anything fancy, and know that structure of data wont change in future
$keys = [];
$for($i=0;$i<$array['floorplans'];++$i) {
if(isset($array['floorplans_'.$i.'_valid_for_export']) && $array['floorplans_'.$i.'_valid_for_export']===1) {
$keys[] = $i;
}
}
print_r($keys);

How to add array if key value is same

Hi i having difficulty to trace an multi dimensional array.
[
0 => array:7 [
"date" => "2016-01-19"
"placement_id" => 1
"requests" => 18
"revenue" => 1
],
1 => array:7 [
"date" => "2016-01-19"
"placement_id" => 1
"requests" => 2
"revenue" => 0.2
]
];
if placement_id are same i want resulted array:
1 => array:7 [
"date" => "2016-01-19"
"placement_id" => 1
"requests" => 20
"revenue" => 1.2
]
The requirement is to produce an output array that has:
Items with the same 'placement_id' having the 'requests' and revenue summed.
The key of the entry in the output array will be be the 'placement_id'.
That means that the output array will be smaller that the input array.
I decided to use the array_reduce function. There is no special reason, foreach loops work fine. It isn't any more efficient. It is just different.
The important point about array_reduce is that the $carry (accumulator) can be an array...
Working example at Eval.in
The code:
$outArray = array();
$outArray = array_reduce($src,
function($carry, $item) { // accumulate values if possible
$carryKey = $item['placement_id']; // array key
if (isset($carry[$carryKey])) { // accumulate values
$carry[$carryKey]['requests'] += $item['requests'];
$carry[$carryKey]['revenue'] += $item['revenue'];
} else { // is new - add to the output...
$carry[$carryKey] = $item;
}
return $carry;
},
array() /* accumulator ($carry) is an internal variable */);
Output Array:
array (2) [
'1' => array (4) [
'date' => string (10) "2016-01-19"
'placement_id' => integer 1
'requests' => integer 20
'revenue' => float 1.2
]
'666' => array (4) [
'date' => string (10) "2016-04-01"
'placement_id' => integer 666
'requests' => integer 266
'revenue' => float 666.20000000000005
]
]
Test Data:
$src = array(
0 => array(
"date" => "2016-01-19",
"placement_id" => 1,
"requests" => 18,
"revenue" => 1,
),
1 => array(
"date" => "2016-04-01",
"placement_id" => 666,
"requests" => 266,
"revenue" => 666.2,
),
2 => array(
"date" => "2016-01-19",
"placement_id" => 1,
"requests" => 2,
"revenue" => 0.2,
),
);
Taking that $arr parameter is the array that you show, we could create a function like this to look for duplicates ids and aggregate them. The $output array will return the results.
public function checkArray($arr) {
$output = array();
$deleted = array();
foreach($arr as $key => $value){
if (!in_array($key, $deleted)) {
$entry = array();
$entry['date'] = $value['date'];
$entry['placement_id'] = $value['placement_id'];
$entry['requests'] = $value['requests'];
$entry['revenue'] = $value['revenue'];
foreach($arr as $key2 => $value2){
if($key != $key2 && $value['placement_id'] == $value2['placement_id']){
$entry['requests'] += $value2['requests'];
$entry['revenue'] += $value2['revenue'];
$deleted[] = $key2;
}
}
$output[] = $entry;
}
}
return $output;
}

How to compare three values in a array and merge?

How can i merge array with the same value?
I have three array which are $participants, $conferance_participants and $contacts
i want to compare values with this three array and merge
for example :
if $participants['calleridnum'] == $conferance_participants['uid'] == $contacts['name']
i want the output to be like this :
Array
(
[0] => Array
(
[calleridnum] => 1
[test] => yay
[uid] => 1
[channel] => deze
[name] => 1
[limit] => 1
)
)
this is my code so far:
<?php
$participants = [
[ 'calleridnum' => 1,
'test' => 'yay'
]
];
$conferance_participants = [
[ 'uid' => 1,
'test' => 'yay2',
'channel' => 'deze'
]
];
$contacts = [
[ 'name' => 1,
'test' => 'yay2',
'limit' => 1
]
];
foreach ($participants as $participant=>$p) {
foreach ($conferance_participants as $conferance_participant=>$c) {
foreach ($contacts as $contact=>$cs) {
if (($p['calleridnum'] == $c['uid']) && ($c['uid'] == $cs['name'])) {
foreach ( $c as $key=>$val ) {
if (!isset($p[$key])) {
$participants[$participant][$key] = $val;
}
}
}
}
}
}
print_r( $participants );
?>
Try to call array_merge() , but you still have to consider the different values with the same key (eg. the values of key 'test' )
if (($p['calleridnum'] == $c['uid']) && ($p['uid'] == $c['name'])) {
$participants[$participant] = array_merge(
$participants[$participant],
$conferance_participants[$conferance_participant],
$contacts[$contact]
);
}

Filter multidimensional array by lowest price

I'm working with an array that I'd like to filter so it only contains the lowest prices per key. So 50 would only have one unit, same with 100, and that unit would be the lowest price.
Here's an example of what I'm working with:
$units = [
50 => [
41788 => ['StdRate' => 231.0000, 'UnitName' => "NN23"],
46238 => ['StdRate' => 303.0000, 'UnitName' => "1038"],
46207 => ['StdRate' => 303.0000, 'UnitName' => "1007"]
],
100 => [
41570 => ['StdRate' => 299.0000, 'UnitName' => "HH18"],
46214 => ['StdRate' => 388.0000, 'UnitName' => "1014"]
]
];
I wanted to avoid doing this with a complicated foreach loop, so I thought an array_filter would be nice, but having a hard time wrapping my head around it. Or would a foreach be best?
$filtered = array_filter($units, function($a) {
});
Expected Output:
[
50 => [
41788 => ['StdRate' => 231.0000, 'UnitName' => "NN23"]
],
100 => [
41570 => ['StdRate' => 299.0000, 'UnitName' => "HH18"]
]
];
Here is a function that will go through your multi-dimensional array and grab the lowest units. It will retain the key of the big array (50, 100) and the key of the unit it grabbed (41788, 41570). It will not retain multiple values of the same low rate. In those cases it will return the first of the lowest value it found. Might not be exactly what you want, but it should be a good start and you can always modify it later. It uses a nested foreach to get its work done.
Hope this help you out!
function findLows($big) {
$lowUnits = array();
foreach($big as $id => $array) {
$low = false;
$prev = false;
foreach($array as $k => $a) {
if(!$low) {
$low = $k;
$prev = $a['StdRate'];
} else {
if($a['StdRate'] < $prev) {
$prev = $a['StdRate'];
$low = $k;
}
}
}
$lowUnits[$id] = array( $low => $array[$low]);
}
return $lowUnits;
}
$bigArray = array();
$bigArray[50][41788] = array('StdRate' => 231.0000, 'UnitName' => "NN23");
$bigArray[50][46238] = array('StdRate' => 303.0000, 'UnitName' => "1038");
$bigArray[50][46207] = array('StdRate' => 303.0000, 'UnitName' => "1007");
$bigArray[100][41570] = array('StdRate' => 299.0000, 'UnitName' => "HH18");
$bigArray[100][46214] = array('StdRate' => 388.0000, 'UnitName' => "1014");
$filtered = findLows($bigArray);
var_dump($filtered);
Will produce:
array(2) {
[50]=>
array(1) {
[41788]=>
array(2) {
["StdRate"]=>
float(231)
["UnitName"]=>
string(4) "NN23"
}
}
[100]=>
array(1) {
[41570]=>
array(2) {
["StdRate"]=>
float(299)
["UnitName"]=>
string(4) "HH18"
}
}
}
For an array with 1 fewer levels of depth, you could have directly iterated the data with array_filter(). Because you want to filter each set of data relating to first level entries, you just need to nest the array_filter() inside of array_map() (for a functional-style script).
I am going to isolate the StdRate values in each set and determine the lowest value by calling min() on the temporary array generated by array_column().
To pass the $min value into the filter's scope, use use().
This snippet will potentially return multiple deep subarrays for a respective set of data IF there is a tie among the lowest values in the set.
Code: (Demo)
$units = [
50 => [
41788 => ['StdRate' => 231.0000, 'UnitName' => "NN23"],
46238 => ['StdRate' => 303.0000, 'UnitName' => "1038"],
46207 => ['StdRate' => 303.0000, 'UnitName' => "1007"]
],
100 => [
41570 => ['StdRate' => 299.0000, 'UnitName' => "HH18"],
46214 => ['StdRate' => 388.0000, 'UnitName' => "1014"]
]
];
var_export(
array_map(
function($unit) {
$min = min(array_column($unit, 'StdRate'));
return array_filter(
$unit,
function($row) use ($min) {
return $row['StdRate'] == $min;
}
);
},
$units
)
);
Output:
array (
50 =>
array (
41788 =>
array (
'StdRate' => 231.0,
'UnitName' => 'NN23',
),
),
100 =>
array (
41570 =>
array (
'StdRate' => 299.0,
'UnitName' => 'HH18',
),
),
)

Categories