簡體   English   中英

PHP從多維數組中刪除特定數組

[英]PHP removing a specific array from a multidimensional array

我在PHP中有一個多維數組,我需要根據其中一個數組中一項的值刪除一個數組:

示例數組

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")
)

我知道我想刪除鍵0中包含joe的數組,但是我只想刪除鍵1中包含最新日期的joe數組。 以下輸出是我要完成的工作:

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

除了循環遍歷每個數組,是否有一種簡單的方法可以在PHP中執行此操作?

這是一種非循環方法,該方法使用array_intersect和array_column查找“喬的”,然后刪除最大的array_key,因為我首先對日期進行了排序。

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

如果要重置數組中的鍵,請編輯忘記添加array_values()。

只需添加$arr = array_values($arr); 取消設定后。

我會這樣處理:

<?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);

不知道您是否不想循環使用主體或什么……我傾向於閱讀。 查找所有出現的joe 按日期排序。 通過密鑰刪除最新的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM