Search code examples
phparraysarray-push

Splitting Array PHP


I have been trying to split an array into two groups currently my array looks like this.

Array
(
    [cities] => Array
        (
            [0] => Array
                (
                    [id] => 0
                    [storename] => test
                    [notes] => test
                    [rejected] => off
                    [offer] => 
                    [time] => 1393585744241
                )

            [1] => Array
                (
                    [id] => 1
                    [storename] => test2
                    [notes] => test2
                    [rejected] => on
                    [offer] => test2
                    [time] => 1393585751264
                )

        )

)

PHP

foreach( $array['cities'] as $data)
{
    if($data['rejected'] == "off"){

        $rejected = array();

        array_push($rejected, $data['id'], $data['storename'], $data['offer']);


    }

    if($data['rejected'] == "on"){

        $nonerejected = array();

        array_push($nonerejected, $data['id'], $data['storename'], $data['offer']);


    }


}

Any ideas where i'm going wrong?


Solution

  • Try this,

    $nonerejected = array();
    $rejected = array();
    foreach( $array['cities'] as $data)
    {
        if($data['rejected'] == "off"){
            array_push($rejected, $data['id'], $data['storename'], $data['offer']);
        }
    
        if($data['rejected'] == "on"){
            array_push($nonerejected, $data['id'], $data['storename'], $data['offer']);
        }
    }
    

    You should declare the $nonerejected and $rejected array outside foreach loop