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.

3
  • you can use array_values for it. see stackoverflow.com/questions/6446942/php-convert-array-keys Commented Feb 21, 2014 at 5:06
  • In addition to @SatishSharma answer you will need array_keys too I think. Not sure though how fast (faster) this would be than your solution. Commented Feb 21, 2014 at 5:09
  • Is it an associative array or an object? Based on what you posted it appears to be the latter. Commented Feb 21, 2014 at 5:10

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

Comments

0

https://www.php.net/array_column

may be this could solve your problem!!

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.