1

Suppose I have an SQL Statement that looks like:

SELECT * FROM myTable;

Now back in PHP I have a result array $result[], How can I iterate through that array and print out the values if I don't know the column names? Can I interrogate the array somehow?

Background: I have a table, I've rendered the table headings based on the a metadata table, now I need to populate the data, but I only want to pull out the field names that match the table headers and insert them into the HTML Table.

This process is happening dynamically, every table is different and has different field names (discovered by interrogating the metadata), but shares the same php code, so it needs to be flexible and smart enough to figure out what to render.

1
  • You can always use a key of an associative array which will be your column name. Commented Jan 29, 2014 at 5:03

2 Answers 2

1

Edit: I now understand that your $result is an array of arrays.

foreach ($result as $row) {
    foreach ($row as $key => $value) {
      print "column $key has value $value\n";
    }
}

Or you can call array_keys($row) to return the keys of an associative array.

Sign up to request clarification or add additional context in comments.

2 Comments

I see where you're going and it makes total sense, but when I go to echo $value it errors (Array to string conversion) and just prints the word array
Disregard, $result was a multidimensional array, needed to do a second foreach()
0

You can use foreach loop with key-value pair in that case.

You can use it like this,

foreach($result as $key=>$value) {
    //$key returns the key of $result array
    //$value returns the respective value of that key
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.