phparraysmultidimensional-arraymerging-data

Append associatve elements to each row while looping a mysqli query result


I am using the following code to generate additional data for each row of my query result set.

while ($row = $table->fetch_array()) {
    $formula = [
        'tkoSum' => $this->getTkoSum($row['id']),
        'chko' => $this->getChko($row['id'])
    ];
    $containers[] = ['info' => $row, 'formula' => $formula];
}

My current result ($containers) is:

[
    0 => [
        'info' => ['id' => 1, 'category' => 'МКД'],
        'formula' => ['tkoSum' => '12', 'chko' => '15']
    ],
    1 => [
        'info' => ['id' => 2, 'category' => 'Офис'],
        'formula' => ['tkoSum' => '62', 'chko' => '45']
    ]
]

But I need a 2d structure with indexed rows containing associative elements like this:

[
    0 => [
        'id' => 1,
        'category' => 'МКД',
        'tkoSum' => '12',
        'chko' => '15'
    ],
    1 => [
        'id' => 2,
        'category' => 'Офис',
        'tkoSum' => '62',
        'chko' => '45'
    ]
];

How can this be achieved?


Solution

  • Append the additional data using the union operator.

    while ($row = $table->fetch_array(MYSQLI_ASSOC)) {
        $containers[] = $row
        + [
            'tkoSum' => $this->getTkoSum($row['id']),
            'chko' => $this->getChko($row['id'])
        ];
    }