4

Imagine I have this array

 $records = array(
array(
    'id' => 2135,
    'first_name' => 'John',
    'last_name' => 'Doe',
),
array(
    'id' => 3245,
    'first_name' => 'Sally',
    'last_name' => 'Smith',
),
array(
    'id' => 5342,
    'first_name' => 'Jane',
    'last_name' => 'Jones',
),
array(
    'id' => 5623,
    'first_name' => 'Peter',
    'last_name' => 'Doe',
)
);

I tried this

 array_keys($records)

But it does not return this

Array
(
    [0] => id
    [1] => first_name
    [2] => last_name
)

I want to know the name of the columns and how many of them to have the possibility to change the query on the database and have the table with the right amount of columns right away

Alexandre Calvario
  • 143
  • 1
  • 1
  • 11

2 Answers2

4

Assuming in your array you have at least one row, all rows have the same columns, you could do:

<?php
    $numColumns = count($records[0]);
    $numRows = count($records);
    $columnsNames = array_keys($records[0]);
?>

This is because you have an array of arrays, so it is correct to use array_keys(), you just need to do it on one (in this case the first) of the arrays contained in $records

MazzCris
  • 1,812
  • 1
  • 14
  • 20
3

I don't understand MazzCris's answer, so I'll answer the question as I understand it.

Access the first subarray, then extract the keys.

Code: (Demo)

$keys = array_keys($records[0]);
var_export($keys);
echo "\n";
echo "Number of columns: " , count($keys);

Output:

array (
  0 => 'id',
  1 => 'first_name',
  2 => 'last_name',
)
Number of columns: 3
mickmackusa
  • 43,625
  • 12
  • 83
  • 136