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
  • 15,166
  • 34
  • 100
  • 153
  • 1
    Edit your question and show the SQL query that produces the result. You may be able to use GROUP_CONCAT to produce the result without loops. – Sloan Thrasher May 10 '18 at 14:40
  • @SloanThrasher Example query added. – David May 10 '18 at 14:44
  • 1
    Possible duplicate of [How to get an array of specific "key" in multidimensional array without looping](https://stackoverflow.com/questions/7994497/how-to-get-an-array-of-specific-key-in-multidimensional-array-without-looping) – Matt Raines May 10 '18 at 14:59

3 Answers3

6

This should do it for PHP 5.5+

$result = array_column($array, 'ID');
AbraCadaver
  • 77,023
  • 7
  • 60
  • 83
Vlad Preda
  • 9,535
  • 7
  • 32
  • 62
2

You can use array_map():

$new_array = array_map(function($v){return $v['ID'];}, $old_array);
MonkeyZeus
  • 19,651
  • 3
  • 32
  • 72
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,888
  • 2
  • 21
  • 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