Adam
Adam

Reputation: 1309

Convert multidimensional array to multidimensional associative array

and my question:

Convert numeric multidimensional array generated from array_chunk to a associative array or stdClass. How do i do it?

I generate a array from

    foreach($xpath->query("./td[position()=2 ]", $row) as $cell)
    {
        $a[] = trim($cell->nodeValue);
    }

This array

looks like:

Array
(
    [0] => AAK AB
    [1] => 642,00
    [2] => 644,00
    [3] => 635,00
    [4] => 17 108 677
    [5] => ABB Ltd
    [6] => 164,90
    [7] => 165,00
    [8] => 163,20
    [9] => 146 251 251
...

But with array_chunk, i generate:

Array
(
    [0] => Array
        (
            [0] => AAK AB
            [1] => 642,00
            [2] => 644,00
            [3] => 635,00
            [4] => 17 243 497
        )

    [1] => Array
        (
            [0] => ABB Ltd
            [1] => 164,80
            [2] => 165,00
            [3] => 163,20
            [4] => 146 335 464
        )

But for cleaner and more understandable code, i would like it to look like:

                   Array
(
    [1] => stdClass Object
        (
            [stock] => AAK AB
            [prev] => 634,50
            [high] => 638,50
            [low] => 622,50
            [rev] => 32 094 048
        )

    [2] => stdClass Object
        (
            [stock] => ABB Ltd
            [prev] => 162,80
            [high] => 163,30
            [low] => 161,90
            [rev] => 167 481 268
        )
) 

It doesn't have to be a stdClass, but if it is possible to echo data from array with objects like:

$a->aktie or $a['aktie']

Upvotes: 1

Views: 448

Answers (1)

Sougata Bose
Sougata Bose

Reputation: 31749

You can try array_combine in a loop after array_chunk -

$keys = array('stock', 'prev', 'high', 'low', 'rev');
foreach($your_array as &$array) {
    $array = (object) array_combine($keys, $array);
} 

Upvotes: 2

Related Questions