How to write loop inside return statement?

I need get this result

return [
    [$row_0['Наименование'], $row_0['Ассортимент'], $row_0['Сумма']],
    [$row_1['Наименование'], $row_1['Ассортимент'], $row_1['Сумма']],
    [$row_2['Наименование'], $row_2['Ассортимент'], $row_2['Сумма']],
];

By using this loop for parsing database data

for ($i = 0; $i < $num_rows; $i++) {
    $row = $adb->query_result_rowdata($accountQuery, $i);
    [$row['Наименование'], $row['Ассортимент'], $row['Сумма']],
}

This code has syntax error

return [
    for ($i = 0; $i < $num_rows; $i++) {
        $row = $adb->query_result_rowdata($accountQuery, $i);
        [$row['Наименование'], $row['Ассортимент'], $row['Сумма']],
    }
];

How to write loop to get above described result in return statement?

Upvotes: 2

Views: 107

Answers (3)

Hero Wanders
Hero Wanders

Reputation: 3292

If you really need the full result array immediately, others have already provided the answer you want.

In case you just want to iterate over the array once, using the yield keyword (generator syntax) may give you another quite readable solution:

for ($i = 0; $i < $num_rows; $i++) {
    $row = $adb->query_result_rowdata($accountQuery, $i);
    yield [$row['Наименование'], $row['Ассортимент'], $row['Сумма']];
}

Notice the similarity to the second block of code you have posted.

If calling $adb->query_result_rowdata(...) requires an open database connection (or some other closeable resource), you may close that connection only if you decide that you won't iterate over the resulting generator anymore. Retrieving new values from the generator after closing the connection will return errors.

Upvotes: 1

Kamal Paliwal
Kamal Paliwal

Reputation: 1301

Just do all the stuff before the return statement and return array like this:

$result = [];
for ($i = 0; $i < $num_rows; $i++) {
    $row = $adb->query_result_rowdata($accountQuery, $i);
    $result[] = [$row['Наименование'], $row['Ассортимент'], $row['Сумма']];
}
return $result;

Upvotes: 0

Qirel
Qirel

Reputation: 26450

You cannot have a controlstructure within a return statement.

Loop over the data first, append it to an array, and return that instead.

$result = array();
for ($i = 0; $i < $num_rows; $i++) {
    $row = $adb->query_result_rowdata($accountQuery, $i);
    $result[] = [$row['Наименование'], $row['Ассортимент'], $row['Сумма']];
}
return $result;

Upvotes: 5

Related Questions