skip to Main Content

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?

4

Answers


  1. Well, assuming the category value comes from the associative array in $row, would the following work?

        while ($row = $table->fetch_array()) {
        $containers[] = [$row['id'], $row['category'], $this->getTkoSum($row['id']), $this->getChko($row['id'])];
    }
    
    Login or Signup to reply.
  2. What about this?

    while ($row = $table->fetch_array()) {
        $vals_arr = array();
    
        foreach($row as $next_val) {
            $vals_arr[] = $next_val;
        }
    
        $containers[] = [implode(', ', $next_val), $this->getTkoSum($row['id']), $this->getChko($row['id'])];
    }
    
    Login or Signup to reply.
  3. you can do this;

    $newContainers = [];
    
    foreach ($containers as $key => $container) {
        $newContainers[$key] = [
            'id' => $container['info']['id'],
            'category' => $container['info']['category'],
            'tkoSum' => $container['formula']['tkoSum'],
            'chko' => $container['formula']['chko']
        ];
    }
    
    print_r($newContainers);
    

    or if you want keys to be not hardcoded;

    $newContainers = [];
    
    foreach ($containers as $key => $container) {
        $newContainer = [];
        foreach ($container as $subArray) {
            foreach ($subArray as $subKey => $subValue) {
                $newContainer[$subKey] = $subValue;
            }
        }
        $newContainers[$key] = $newContainer;
    }
    
    print_r($newContainers);
    
    Login or Signup to reply.
  4. 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'])
        ];
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search