Forum Moderators: coopster

Message Too Old, No Replies

MySQLi, I just want a simple array of the result without a loop

         

csdude55

5:10 am on Oct 7, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Let's say I have this:

$sth = query('SELECT col FROM table');
$arr = mysqli_fetch_all($sth, MYSQLI_NUM);


It works, but I end up with a confusing array of arrays:

Array
(
[0] => Array
(
[0] => foo
)

[1] => Array
(
[0] => bar
)

[2] => Array
(
[0] => lorem
)
)

I know that I could run it through a loop to make it a regular array:

foreach ($arr as $key => $val)
$newArr[] = $val[0];

print_r($newArr);

// Array
// (
// [0] => foo
// [1] => bar
// [2] => lorem
// )


but that seems like a total waste of resources.

Is there a way to set all of the results to a numeric array like that without a loop?

Dimitri

1:13 pm on Oct 11, 2022 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member Top Contributors Of The Month



What about mysqli_fetch_array ? [php.net...]

robzilla

4:55 pm on Oct 11, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



With mysqli, no. With PDO, you could use FETCH_KEY_PAIR to create an array of simple key-value pairs based on a two-column result set.

What about mysqli_fetch_array?

Still requires a loop.

Dimitri

5:11 pm on Oct 11, 2022 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member Top Contributors Of The Month



My bad, I misread the question.

You can do that :
$newArr=array_column($arr,0);