2

I created a working function for splitting following associative array into two numeric array. I wonder if there is a better method , avoid looping.

I have an array as follows.

Array
(
    [0] => stdClass Object
        (
            [CreatedAt] => 16/02/2014
            [Occurrence] => 1
        )

    [1] => stdClass Object
        (
            [CreatedAt] => 17/02/2014
            [Occurrence] => 8
        )

    [2] => stdClass Object
        (
            [CreatedAt] => 18/02/2014
            [Occurrence] => 4
        )

    [3] => stdClass Object
        (
            [CreatedAt] => 20/02/2014
            [Occurrence] => 11
        )

)

Need to convert it into two numerical array

Array
(
    [0] => 16/02/2014
    [1] => 17/02/2014
    [2] => 18/02/2014
    [3] => 20/02/2014
)

Array
(
    [0] => 1
    [1] => 8
    [2] => 4
    [3] => 11
)

I used a foreach loop

$array1 = array();
$array2 = array();
foreach ($mainArray as $key => $value) {
    $array1[] = $value->CreatedAt;
    $array2[] = $value->Occurrence;
}
print_r($array1);
print_r($array2);

But if I have 1000 rows in mainArray, it will affect the performance. If you have a better solution, let us all know that.

Sajith
  • 2,842
  • 9
  • 37
  • 49

2 Answers2

0

Try this one:

$objName = (object) array('aFlat' => array());

    array_walk_recursive($array, create_function('&$v, $k, &$t', '$t->aFlat[] = $v;'), $objName);

    var_dump($objName->aFlat);

REFER: How to "flatten" a multi-dimensional array to simple one in PHP?

Community
  • 1
  • 1
Mani
  • 888
  • 6
  • 19
0

http://in1.php.net/array_column

may be this could solve your problem!!

  • It's a good solution. But array_column is available in php 5.5 and above. Most of the servers are running in php 5.3 and 5.4. – Sajith Feb 25 '14 at 04:13