Ibrahim Azhar Armar
Ibrahim Azhar Armar

Reputation: 25745

How do i split this array into two?

I have this array.

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

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

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

)

i want to split the array into two.

1. array with all boolean value true

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

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

)

2. array with all boolean value false

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

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

How do i do it?

thank you..

Upvotes: 1

Views: 104

Answers (3)

dyesdyes
dyesdyes

Reputation: 1217

As your array is a 2 level array, you will need to use 2 loops.

$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;
    }
}

A 3 level array would be:

$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;
        }
    }
}

Upvotes: 0

Karoly Horvath
Karoly Horvath

Reputation: 96258

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');
};

or

$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; } );
};

Upvotes: 1

hakre
hakre

Reputation: 197659

  1. initialize the two new arrays
  2. foreach the input array
  3. foreach the inner array of each input array entry
  4. according to the value set the one or the other of the two new arrays
  5. done.

Example:

$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;

Upvotes: 2

Related Questions