how to ommit array from multidimensional array based on their values
how to ommit array from multidimensional array based on their values
I have an input array:
Array(
Array(
[vehicle] => BUS NO.1
[trip_name] => Trip00011
[running_km] => 5000
)
Array(
[vehicle] => BUS NO.2
[trip_name] => Trip00021
[running_km] => 2400
)
Array(
[vehicle] => BUS NO.1
[trip_name] => Trip00011
[running_km] => 0
)
Array(
[vehicle] => BUS NO.2
[trip_name] => Trip00011
[running_km] => 0
)
Array(
[vehicle] => BUS NO.2
[trip_name] => Trip00021
[running_km] => 0
)
)
I need to change this array into:
Array(
Array(
[vehicle] => BUS NO.1
[trip_name] => Trip00011
[running_km] => 5000
)
Array(
[vehicle] => BUS NO.2
[trip_name] => Trip00021
[running_km] => 2400
)
Array(
[vehicle] => BUS NO.2
[trip_name] => Trip00011
[running_km] => 0
)
)
Please look in to two arrays. I need to omit running_km => 0 array based on the value present in running_km for same vehicle and same trip_name. Could you please help me to do this.
running_km => 0
running_km
vehicle
trip_name
Possible duplicate of merge multidimensional array with sum of values
– Michel
Sep 15 '18 at 8:10
Doesn't my answer work for you @miya?
– Andreas
Sep 16 '18 at 9:15
1 Answer
1
If you loop the array you can build a compound array key. (Example: 'BUS NO.2 Trip00021').
And if the the running km is more then overwrite the item in the new array.
After the loop I do a array_values to remove the associative array keys to indexed array keys.
foreach($arr as $item)
$key = $item['vehicle'] . $item['trip_name'];
if(isset($new[$key]))
if($item['running_km'] > $new[$key]['running_km']) $new[$key] = $item;
else
$new[$key] = $item;
$new = array_values($new);
var_dump($new);
Output:
array(3)
[0]=>
array(3)
["vehicle"]=>
string(8) "BUS NO.1"
["trip_name"]=>
string(9) "Trip00011"
["running_km"]=>
string(4) "5000"
[1]=>
array(3)
["vehicle"]=>
string(8) "BUS NO.2"
["trip_name"]=>
string(9) "Trip00021"
["running_km"]=>
string(4) "2400"
[2]=>
array(3)
["vehicle"]=>
string(8) "BUS NO.2"
["trip_name"]=>
string(9) "Trip00011"
["running_km"]=>
string(1) "0"
https://3v4l.org/4qX7q
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy
This question lacks any code to show us that you've made any attempt to solve this yourself. If you've tried something, show us what you've tried, example of the expected output and what you're actually getting. If you haven't tried anything, you need to do that before posting. We can help you with your existing code, but we won't write it for you. SO is not a free coding service. Please read: How to create a Minimal, Complete, and Verifiable example and also How do I ask a good question?
– Magnus Eriksson
Sep 15 '18 at 5:50