0

I'm trying to a straightforward resultset as an array, from CodeIgniter, and I cannot figure out what I'm doing wrong. Maybe something has changed with CodeIgniter 3.0.4 which I am now using.

I'm trying to get a simple array that I can pass directly to a view dropdown box. Instead I am getting a multi dimensional array which I have to decode.

I've tried various methods without success:

  • result()
  • result_array()
  • row_array()

What on earth am I missing?

$strSQL = "SELECT DISTINCT PurchasingGroup FROM snapshot";
$query=$this->db->query($strSQL);
$data=$query->result_array();

Array ( [0] => Array ( [PurchasingGroup] => AAA ) [1] => Array ( [PurchasingGroup] => BBB ) [2] => Array ( [PurchasingGroup] => CCC ) [3] => Array ( [PurchasingGroup] => DDD) [4] => Array ( [PurchasingGroup] => EEE ) [5] => Array ( [PurchasingGroup] => P&P Deve ) [6] => Array ( [PurchasingGroup] => FFF ) [7] => Array ( [PurchasingGroup] => GGG ) [8] => Array ( [PurchasingGroup] => HHH ) [9] => Array ( [PurchasingGroup] => III ) [10] => Array ( [PurchasingGroup] => JJJ ) [11] => Array ( [PurchasingGroup] => KKK) [12] => Array ( [PurchasingGroup] => LLL ) )
1
  • return array_column($this->db->distinct()->select('PurchasingGroup')->get('snapshot'), 'PurchasingGroup'); Commented Mar 4 at 23:17

2 Answers 2

3

make this resultset from multi dimensional array to simple array? if question this ,you can reference follow:

$query = $this->db->query("YOUR QUERY");
foreach ($query->result_array() as $row)
{
    echo $row['title'];
    echo $row['name'];
    echo $row['body'];
    // You can re-assembled into an array
}
Sign up to request clarification or add additional context in comments.

Comments

2

I don't know what you expect, but your result is perfectly normal: it is an array of the rows from your query, and in each row you have the fields (in our case, only one field).

The result is also coherent with Codeigniter documentation.

To obtain single rows, you have to perform a loop, like:

foreach( $data as $row )
{
    // $row['PurchasingGroup'] is your field value
}

If you want a flat-array of PurchasingGroup values, you can use (on PHP >= 5.5) the array_column function:

$flatArray = array_column( $data, 'PurchasingGroup' );

Edit:

On PHP < 5.5, you can simulate array_column in this way:

$flatArray = array_map
(
    function( $row ) { return $row['PurchasingGroup']; }, 
    $data
);

2 Comments

Excellent! Thanks so much, just what I was looking for. $flatArray = array_column( $data, 'PurchasingGroup' );
What is the best method? seems like the array_column is a hacky way to achieve this. Or maybe it's specifically made for that purpose

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.