0

here i have an array that i want to convert the output of.

here is the function:

public function access($key)
{
    $query = $this->db->query("SELECT box_role.group_id FROM box_role INNER JOIN box_menu ON box_role.menu_id=box_menu.id WHERE box_menu.key='$key'")->result_array();
    return $query;
}

and these are the results:

Array (
    [0] => Array (
        [group_id] => 1
    ) 
    [1] => Array ( 
        [group_id] => 2 
    ) 
    [2] => Array ( 
        [group_id] => 4 
    ) 
);

but I would like the output to be like this:

$new_array = array(1, 2, 4);
GiamPy
  • 3,543
  • 3
  • 30
  • 51
  • `$query = array_column($query, 'group_id');` (ps: you really should read the docs - you are totally open to sql injections with this method ...) – Atural Aug 24 '18 at 06:44
  • thats work..... thanks :) – Agis R Herdiana Aug 24 '18 at 06:49
  • @NigelRen i won't do that for an one liner - i'm not the type of guy who wants to collect points by all means ;) – Atural Aug 24 '18 at 06:55
  • @sintakonte, found a way of not having to answer it- I've found something to flag it as a duplicate instead. – Nigel Ren Aug 24 '18 at 07:02
  • Possible duplicate of [Is there a function to extract a 'column' from an array in PHP?](https://stackoverflow.com/questions/1494953/is-there-a-function-to-extract-a-column-from-an-array-in-php) – Nigel Ren Aug 24 '18 at 07:02

2 Answers2

0

strong textthe output is like this

[
  0 => 
    [group_id] => 1,
  1 => 
    [group_id] => 2,
  2 => 
    [group_id] => 4 ,
]

its an array of arrays

if you want the array values only, you can use

array_values($arr)

Shobi
  • 10,374
  • 6
  • 46
  • 82
0

What your are looking for is a function called array_column

In your specific case it should be

public function access($key)
{
    $query = $this->db->query("SELECT box_role.group_id FROM box_role INNER JOIN box_menu ON box_role.menu_id=box_menu.id WHERE box_menu.key='$key'")->result_array();
    $query = array_column($query, 'group_id');

    return $query;
}

you can find more information about that topic on the official docs here

Atural
  • 5,389
  • 5
  • 18
  • 35