我如何将这个阵列分成两个?

时间:2011-09-28 10:27:33

标签: php arrays

我有这个数组。

Array
(
    [name] => Array
        (
            [isRequired] => 1
            [isBetween] => 1
            [isAlphaLower] => 
            [isLength] => 
        )

    [email] => Array
        (
            [isEmail] => 1
        )

    [pPhone] => Array
        (
            [isPhone] => 
        )

)

我想将数组拆分为两个。

1。所有布尔值为true的数组

Array
(
    [name] => Array
        (
            [isRequired] => 1
            [isBetween] => 1
        )

    [email] => Array
        (
            [isEmail] => 1
        )

)

2。所有布尔值为false的数组

Array
(
    [name] => Array
        (
            [isAlphaLower] => 
            [isLength] => 
        )

    [pPhone] => Array
        (
            [isPhone] => 
        )
)

我该怎么做?

谢谢..

3 个答案:

答案 0 :(得分:2)

  1. 初始化两个新数组
  2. 预先输入数组
  3. foreach每个输入数组条目的内部数组
  4. 根据设置两个新数组中的一个或另一个的值
  5. 进行。
  6. 示例:

    $arrayTrue = $arrayFalse = arrray(); # 1
    foreach($arrayInput as $baseKey => $inner) # 2
        foreach($inner as $key => $value) # 3
            if ($value) $arrayTrue[$basekey][$key] = $value; # 4
            else $arrayFalse[$basekey][$key] = $value;
    

答案 1 :(得分:1)

function is_true($var) {
    return $var;
}
function is_false($var) {
    return !$var;
}

$result_true = array();
$result_false = array();
foreach ($array as $k => $a) {
    $result_true[$k] = array_filter($a, 'is_true');
    $result_false[$k] = array_filter($a, 'is_false');
};

$result_true = array();
$result_false = array();
foreach ($array as $k => $a) {
    $result_true[$k] = array_filter($a);
    $result_false[$k] = array_filter($a, function ($x) { return !$x; } );
};

答案 2 :(得分:0)

由于您的数组是2级数组,因此您需要使用2个循环。

$trueValues = array();
$falseValues = array();
foreach($input AS $key=>$firstLevelValue) {
    foreach($firstLevelValue AS $key2=>$secondLevelValue)  {
        if ($secondLevelValue)
            $trueValues[$key][$key2] = $secondLevelValue;
        else
            $falseValues[$key][$key2] = $secondLevelValue;
    }
}

3级数组将是:

$trueValues = array();
$falseValues = array();
foreach($input AS $key=>$firstLevelValue) {
    foreach($firstLevelValue AS $key2=>$secondLevelValue)  {
        foreach($secondLevelValue AS $key3=>$thirdLevelValue)  {
            if ($thirdLevelValue)
                $trueValues[$key][$key2][$key3] = $thirdLevelValue;
            else
                $falseValues[$key][$key2][$key3] = $thirdLevelValue;
        }
    }
}