Question

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?

Was it helpful?

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

OTHER TIPS

You are repeatedly re-creating the arrays. Move $rejected = array() and $nonrejected = array() to be before the foreach loop.

Yo are creating the arrays on each iteration into the foreach loop. You must create the $rejected and the $nonerejected outside the loop, before it:

$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']);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top