Justin Sellers Justin Sellers - 3 months ago 9
MySQL Question

array_column returning 0 results from an array with data

I have some data coming into a page with multiple rows and columns. I am specifically looking to take 1 entire column and put it into another array.

I am using codeigniter and php. The var dump on my page shows that the data in its raw array is arriving just fine. But once I start to try and create a second array on the page, the array returns 0 results.

Here is the var_dump for the original array. For your sanity, ill only post the first sequence.

array(7) { [0]=> object(stdClass)#19 (7) { ["id"]=> string(1) "1"

["serial_number"]=> string(9) "battery 1" ["battery_type"]=> string(4)
"Lipo" ["cell_count"]=> string(1) "4" ["capacity"]=> string(4) "16.8"
["date_submitted"]=> string(19) "0000-00-00 00:00:00"
["user_id_submitted"]=> string(0) "" } [1]=>

Here is the array_column function

$serialnumber = array_column($batteryDb, "serial_number");

and here is the result:

array(0) { }


Ok, var_dump($batteryDb); shows this:

array(7) { 
 [0] => object(stdClass)#19 (7) {                     <----- object  !!
    ["id"]=> string(1) "1" 
    ["serial_number"]=> string(9) "battery 1" 
    ["battery_type"]=> string(4) "Lipo" 
    ["cell_count"]=> string(1) "4" 
    ["capacity"]=> string(4) "16.8" 
    ["date_submitted"]=> string(19) "0000-00-00 00:00:00" 
    ["user_id_submitted"]=> string(0) "" }
 [1] =>

The problem is that this array structure isn't working with array_column on PHP5.

You have an array of objects, but the function expects an array of arrays.

An array of objects on array_column is only supported by PHP7. Referencing: https://github.com/php/php-src/blob/PHP-7.0.0/UPGRADING#L626

The basic solution would be to turn your objects into arrays:

array(7) { 
     [0] => array (7) {                              <----- array !!
        ["id"]=> string(1) "1" 

You can do that using:

  • $array = (array) $object;
  • $array = get_object_vars($object);
  • if multi-dimensional: $array = json_decode(json_encode($object), true);

Give this a try:

$batteryDbArray = json_decode(json_encode($batteryDb), true);

$serial_numbers = array_column($batteryDbArray, 'serial_number');