flaggalagga
flaggalagga

Reputation: 493

A hash::combine array

I have this array from a sql query :

   [0] => Array
    (
        [T1] => Array
            (
                [First] => A
                [Second] => Apples
                [LastChild] => F
            )

        [0] => Array
            (
                [LastChildNb] => 23
            )

    )

I would like to have this result :

   [0] => Array
    (
        [0] => Array
            (
                [First] => A
                [Second] => Apples
                [LastChild] => F
                [LastChildNb] => 23
            )

    )

How do I do this ? I think I should use "hash::combine", but what would the code be ?

Upvotes: 0

Views: 212

Answers (2)

Jan Pešek
Jan Pešek

Reputation: 111

You can do

array_merge($arr[0]['T1'], $arr[0][0])

Where $arr is defined as follows:

$arr = [0 => Array
(
    'T1' => Array
        (
            'First' => 'A',
            'Second' => 'Apples',
            'LastChild' => 'F'
        ),
    0 => Array
        (
            'LastChildNb' => 23
        )

)];

For multiple records in $arr, you can simply cycle over all records and do this merge manually.

However, assuming you're getting the array as a result of a find() method, I suggest you consider using T1__LastChildNb as an alias within the 'fields' of your condition. Simply said, if you have a find like following:

$this->T1->find('all', ['fields' => 'T1.*, (SOME SUBQUERY) AS LastChildNb']);

then modifying it to be

$this->T1->find('all', ['fields' => 'T1.*, (SOME SUBQUERY) AS T1__LastChildNb']);

might be what you're looking for since it will return desired array directly (tested on 2.6).

Let me know if you're interested in more information.

Upvotes: 0

chrisShick
chrisShick

Reputation: 1096

You could do something like this, with $arr being your array above:

$arr = array_reduce($arr, function(&$arr, $v) {
                        return array_merge($arr, (array) $v);
                    }, array());

Upvotes: 0

Related Questions