如何取消动态生成的多维数组

时间:2014-05-26 01:27:14

标签: php arrays multidimensional-array

我正在尝试删除一个数组,其中一个值...(时间)符合特定条件。 \我目前正在使用的代码如下所示:

foreach($_SESSION as $key) {
   foreach($key['time'] as $keys=>$value){
      if(condition){
      unset($key);
   }
}
}

阵列看起来像这样。

Array
    (
[form1] => Array
    (
        [hash] => lFfKBKiCTG6vOQDa8c7n
        [time] => 1401067044
    )

[form5] => Array
    (
        [hash] => TTmLVODDEkI1NrRnAbfB
        [time] => 1401063352
    )

[form4] => Array
    (
        [hash] => XCVOvrGbhuqAZehBmwoD
        [time] => 1401063352
    )

我尝试从这些页面调整解决方案但是没有用。

Remove element in multidimensional array and save

PHP - unset in a multidimensional array

PHP How to Unset Member of Multidimensional Array?

4 个答案:

答案 0 :(得分:2)

在for循环中取消设置可能会导致问题,使用array_filter更容易,更好用于针对此类问题进行优化。以下是如何使用您的示例。 ideone running code

<?php


$ar = Array(
  "form1" => Array
  (
    "hash" => 'lFfKBKiCTG6vOQDa8c7n',
    "time" => '1401067044'
   ),
  "form5" => Array
  (
    "hash" => 'TTmLVODDEkI1NrRnAbfB',
    "time" => '1401063352'
   ),
  "form4" => Array
  (
    "hash" => 'XCVOvrGbhuqAZehBmwoD',
    "time" => '1401063352'
   )
);

$condition = '1401067044';
$newArray = array_filter($ar, function($form) use ($condition) {
    if (!isset($form['time'])) {
      return true;
    }
    return $form['time'] != $condition;
});

var_export($newArray);

array_filter

答案 1 :(得分:2)

如果你想取消它里面的值,一个简单的单一foreach就足够了。考虑这个例子:

$values = array(
    'form1' => array('hash' => 'lFfKBKiCTG6vOQDa8c7n', 'time' => 1401067044),
    'form5' => array('hash' => 'TTmLVODDEkI1NrRnAbfB', 'time' => 1401063352),
    'form4' => array('hash' => 'XCVOvrGbhuqAZehBmwoD', 'time' => 1401063352),
);
$needle = 1401067044;
foreach($values as $key => &$value) {
    if($value['time'] == $needle) {
        // if you want to remove this key pair use this
        unset($values[$key]['time']);
        // if you just want to remove the value inside it
        $value['time'] = null;
        // if you want to remove all of this entirely
        unset($values[$key]);
    }
}

Fiddle

答案 2 :(得分:1)

你需要做

unset($_SESSION[$key])

然而正如胜利所提到的,array_filter可能是一种更好的方法。

答案 3 :(得分:1)

假设您的值存储在$_SESSION

foreach($_SESSION as $key => $value) {
    if(isset($value['time']) && $value['time'] < 1401063352) {
        unset($_SESSION[$key]);
    }
}

如果要将值存储在$ _SESSION中,您可能需要考虑将它们存储在$ _SESSION ['myForms']这样的子字段中,因此如果您需要在会话中添加其他值,您只需轻松访问所需的值