0

I'm wondering what the most efficient way to reduce this array down by a level, ideally without loops in PHP. It's a result from mysqli_fetch_all().

Array
(
    [0] => Array
        (
            [ID] => 648546
        )

    [1] => Array
        (
            [ID] => 648552
        )

    [2] => Array
        (
            [ID] => 650046
        )

    [3] => Array
        (
            [ID] => 652732
        )

    [4] => Array
        (
            [ID] => 652738
        )

    [5] => Array
        (
            [ID] => 652756
        )

)

The result I would like is

array(648546,648552,650046,652732,...)

The simple query example it comes from is something as easy as:

SELECT mytable.ID FROM mytable WHERE status =1
David
  • 16,246
  • 34
  • 103
  • 162

3 Answers3

6

This should do it for PHP 5.5+

$result = array_column($array, 'ID');
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
Vlad Preda
  • 9,780
  • 7
  • 36
  • 63
2

You can use array_map():

$new_array = array_map(function($v){return $v['ID'];}, $old_array);
MonkeyZeus
  • 20,375
  • 4
  • 36
  • 77
2

You might try this:

SELECT GROUP_CONCAT(mytable.ID)
FROM mytable 
WHERE status = 1
GROUP BY status

It should return 1 row with the ID as a comma separated list.

Sloan Thrasher
  • 4,953
  • 3
  • 22
  • 40
  • There is a server defined maximum length of a `GROUP_CONCAT` column. By default I think it's 1,024 characters, so if you have more than 150(ish) 6 digit IDs this won't work. – Matt Raines May 10 '18 at 14:57
  • not pure PHP, but still a fanstastic answer which has also equally solved the problem! – David May 10 '18 at 15:00
  • If you need more than 1024 characters for the result, you can change the max length for the group concat using ```SET group_concat_max_len = val;```. See [group_concat][https://dev.mysql.com/doc/refman/8.0/en/group-by-functions.html#function_group-concat) – Sloan Thrasher May 10 '18 at 15:09