2

I have a $results array produced from a query and I would like to output a table in html. I would like the header to be "id", "length" and "sample_id". Since the header changes every time, so I used

$keys = array_keys($results[0]);

I got "array_keys() expects parameter 1 to be array" error. If the nested part is not an array, how should I get the keys?

array:59 [▼
  0 => {#160 ▼
    +"id": 204
    +"length": 233
    +"sample_id": "ad3"
  }
  1 => {#161 ▼
    +"id": 205
    +"length": 733.5
    +"sample_id": "bt7r"
  }
  2 => {#162 ▶}
  3 => {#163 ▶}
  4 => {#164 ▶}
  5 => {#165 ▶}
3
  • 1
    Your array seems to contain objects, not arrays. Commented Oct 28, 2015 at 15:47
  • change whatever datatype that is to array->get array key-> done?? Commented Oct 28, 2015 at 15:50
  • $keys = get_object_vars( $results[0] ); Commented Oct 28, 2015 at 15:51

1 Answer 1

2

This is because $results is actually an array of objects.

I don't know how you got the array, but one can usually choose how to return the objects.

If you're using PDO, one can use the method $statement->fetchAll();.

One can also get all the "keys" by using the get_object_vars method to get them:

$keys = array_keys(get_object_vars($results[0]));
Sign up to request clarification or add additional context in comments.

1 Comment

I used Laravel Query Builder. The array was generated by : $query->get();

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.