2016-03-26 90 views
0

如果d超過30天,我有這個2d數組並且喜歡拼接或取消設置a,b,c,d。 完全新的PHP陣列任何幫助非常感謝。拼接二維php數組

Array 
(
    [0] => Array (
      [0] => a 
      [1] => b 
      [2] => c 
      [3] => d 
     ) 
    [1] => Array (
      [0] => a 
      [1] => b 
      [2] => c 
      [3] => d 
     ) 
) 


foreach($arr as $a) { 
     if($a[3] + 30 < date) { 
      //??? 
    } 
} 
+0

您是否在尋找未設定功能? – Rizier123

+0

取消設置'a,b,c,d'還是取消設置父數組中的整個數組元素? –

回答

2
foreach($arr as $index => $a) { 
    if($a[3] + 30 < date) { 
    unset($arr[$index]); 
    } 
} 

(和我自己,我會用關聯數組來處理更舒適,使人類可讀)

+0

如果您要從您要傳遞的數組中移除元素,我還會猶豫使用foreach。我忘記了爲什麼。我在變老。 – Gralgrathor

0

下面是一個使用標準date_diff函數和DateTime對象的例子。 date_diff也可以給你在其他面值的差異比天。我通常更喜歡使用標準功能,因爲它支持更多的時區,如時區。

-

<?php 

$d1=new DateTime("2016-03-22"); 
$d2=new DateTime("2015-03-23"); 
$d3=new DateTime("2015-03-24"); 
$d4=new DateTime("2015-03-25"); 
$today= new DateTime(); 

$arr = array(
    array (
      $d1, 
      $d2, 
      $d3, 
      $d4, 
     ), 
    array (
      $d4, 
      $d2, 
      $d3, 
      $d1 
     ) 
); 

$count=0; 
foreach ($arr as &$a) { 
    echo "Element" . $count . ": \r\n"; 
    //print_r(date_diff($a[3], $today)); 
    $difference = date_diff($a[3], $today); 
    if ($difference->days > 30){ 
     echo "Removing. \r\n"; 
     unset($arr[$count]); 

    } 
    else{ 
     echo "Not removing. \r\n"; 
    } 
    $count++; 
} 

print_r($arr); 

?> 

-

輸出:

Element0: Removing. 
Element1: Not removing. 

// Array[0] is removed. 
Array ([1] => Array ([0] => DateTime Object ([date] => 2015-03-25 00:00:00 [timezone_type] => 3 [timezone] => America/New_York) [1] => DateTime Object ([date] => 2015-03-23 00:00:00 [timezone_type] => 3 [timezone] => America/New_York) [2] => DateTime Object ([date] => 2015-03-24 00:00:00 [timezone_type] => 3 [timezone] => America/New_York) [3] => DateTime Object ([date] => 2016-03-22 00:00:00 [timezone_type] => 3 [timezone] => America/New_York)))