2016-03-26 15 views
0

私はこの2次元配列を持ち、dが30日以上経過した場合にa、b、c、dをスプライスまたはアンセットするのが好きです。 php配列を完全に新しくしてくれてありがとうございました。2次元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)))