Austin
Austin

Reputation: 1627

PHP removing a specific array from a multidimensional array

I have a multidimensional array in PHP where I need to remove one array based on the value of an item in one of the arrays:

Example Array

array(
   "0"=>array("0"=>"joe", "1"=>"2018-07-18 09:00:00"),
   "1"=>array("0"=>"tom", "1"=>"2018-07-17 09:00:00"),
   "2"=>array("0"=>"joe", "1"=>"2018-07-14 09:00:00")
)

I know that I want to remove the array that contains joe in key 0, but I only want to remove the array that contains joe with the most current date in key1. The following output is what I'm trying to accomplish:

array(
   "0"=>array("0"=>"tom", "1"=>"2018-07-17 09:00:00"),
   "1"=>array("0"=>"joe", "1"=>"2018-07-14 09:00:00")
) 

Is there a simple way to do this in PHP aside from looping through each array?

Upvotes: 0

Views: 87

Answers (2)

ficuscr
ficuscr

Reputation: 7054

I would go about it like this:

<?php
 $foo = array(
   "0"=>array("0"=>"joe", "1"=>"2018-07-18 09:00:00"),
   "1"=>array("0"=>"tom", "1"=>"2018-07-17 09:00:00"),
   "2"=>array("0"=>"joe", "1"=>"2018-07-14 09:00:00")
);


$tmp = [];  
foreach($foo as $k => $v) {
    if ($v[0] === 'joe') {
        $tmp[$v[1]] = $k;
    }
}
if (!empty($tmp)) {
    sort($tmp);  //think that is sane with date format?
    unset($foo[reset($tmp)]);
}

var_dump($foo);

Not sure if you don't want to loop on principal or what... I tend to go for readability. Find all occurrences of joe. Sort on date. Remove the most recent by key.

Upvotes: 1

Andreas
Andreas

Reputation: 23958

Here is a non looping method that uses array_intersect and array_column to find the "Joe's" and then deletes the maximum array_key since I first sort the array on dates.

usort($arr, function($a, $b) {
    return $a[1] <=> $b[1];
}); // This returns the array sorted by date

// Array_column grabs all the names in the array to a single array.
// Array_intersect matches it to the name "Joe" and returns the names and keys of "Joe"
$joes = array_intersect(array_column($arr, 0), ["joe"]);

// Array_keys grabs the keys from the array as values
// Max finds the maximum value (key)
$current = max(array_keys($joes));
unset($arr[$current]);

var_dump($arr);

https://3v4l.org/mah6K

Edit forgot to add the array_values() if you want to reset the keys in the array.

Just add $arr = array_values($arr); after the unset.

Upvotes: 3

Related Questions