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.
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.
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
}
Related
I feel like i'm missing something quite simple. What are some of the best ways to iterate through combinations of $key names -- doing something different for each-- in a php foreach loop?
I have a number of values in an array with key values that follow the same naming format.
Example:
$rec_items['title3'] = implode($meta['title3']);
$rec_items['title4'] = implode($meta['title4']);
$rec_items['title5'] = implode($meta['title5']);
The $rec_items array also contains other values that do not follow this naming convention (or data type).
I'm looping through $rec_items with a foreach loop. I would like to be able to dynamically cycle through key names in $rec_items, and 'do something' when a key is found that matches title*. I've tried pushing numeric numbers from a counter variable into key names to be searched for (like below):
foreach ($rec_items as $key => $value){
$c = 0;
if(!empty($key[${'title'.$c}]){
$c++;
//do something
}
I believe that I cannot pass the value ${'title'.$c} into $key[] and have tried to pass the value of ${'title'.$c} as a string with no luck.
I just share the above to try to highlight what i'm trying to achieve.
(1) dynamically loop through key names in the format 'title*'
(2) if the key name is present in the $rec_items array ... do something.
I'm not sure what your original code was trying for; you appeared to be treating the array key like an array itself? Using a variable variable? Anyway, you just need a simple string search of the key. You can use regular expressions or whatever you like for more complex matching.
<?php
$rec_items = ["foo"=>12, "bar"=>34, "title1"=>56, "title2"=>78, "baz"=>90];
foreach ($rec_items as $k=>$v) {
if (strpos($k, "title") === 0) {
echo "$k = $v\n";
}
}
Output:
title1 = 56
title2 = 78
I have an object of query results. Each result has two columns: abbreviation and text. I need to create a new array, where I want to store values from 'text' column grouped by values in 'abbreviation' column.
I tried this:
foreach ($results as $result) {
$results_by_book_abbreviation[$result->abbreviation] = $result->text;
}
What I get is an array with multiple keys, but each key has only one value, but my object has multiple values with the same key.
It worked in PHP 5.5.38, now I have PHP 7.0.13
Array KEYS are UNIQUE, so if you load a key more than once you are overwriting it's contents each time.
So create an array below $results_by_book_abbreviation[$result->abbreviation] like this
foreach ($results as $result) {
$results_by_book_abbreviation[$result->abbreviation][] = $result->text;
// the change ^^
}
This would have been wrong in any version of PHP so it is not related to you changing the version of PHP that is running this code
You need to create an array of array as follows:
foreach ($results as $result)
{
if(!isset($results_by_book_abbreviation[$result->abbreviation]))
{
$results_by_book_abbreviation[$result->abbreviation] = array();
}
$results_by_book_abbreviation[$result->abbreviation][] = $result->text;
}
This is really a dumb question from a beginner, I have a table called "stations" inside my database and on it I have a column called "keywords".
I need to retrieve all those rows that contain one specific keyword (let's say "pizza").
I tried with this but it didn't work:
foreach ($stations->result() as $row)
{
foreach ($row->keywords as 'pizza')
{
<--my code-->
}
}
How could I retrieve all rows that contain "pizza" inside a specific column using PHP?
You can accomplish this using explode() to turn the list into an array. Then you can use in_array():
foreach ($stations->result() as $row) {
if ( in_array('pizza', explode(",", $row->keywords) ) ) {
<--my code-->
}
}
explode(",", $row->keywords) turns your comma-separated list into an array.
in_array('pizza', $array ) returns TRUE if pizza is found, otherwise it returns FALSE.
Instead of parsing it in PHP, you can select only the relevant rows using find_in_set:
SELECT *
FROM stations
WHERE FIND_IN_SET ('pizza', keywords) > 0
We have a nasty database call using the Wordpress function $wpdb->get_results(SQL).
After receiving the result in PHP, we need to make a few changes to the result.
So can anyone tell me how I can:
1) Remove specific rows from the get_results() returned object.
2) Change the values of the specific columns in specific rows in the returned object.
I.e. if the object returned is $nastyData, we need to:
1) Remove specific rows from $nastyData
2) Change the value of specific columns in specific rows in $nastyData, for example $nastyData->name for a specific row.
Any ideas?
I have thought about makeing get_results() return the data as an array, but that will create problems in other places in our code (where the code expects to receive an object).
Thanks,
Mads
To start with, your "Nasty database call" should be optimized to be less nasty. More specifically, only query the results you want so that you don't have to remove stuff afterwords. This is the best solution.
If you insist on trying to modify the objects, this is a workaround. According to the documentation, when returning objects, they are returned in one of two ways:
OBJECT - result will be output as a numerically indexed array of row objects.
OBJECT_K - result will be output as an associative array of row objects, using first column's values as keys (duplicates will be discarded).
So, knowing that the result is an array of objects, we can get to each individual instance using a foreach construct:
$results = $wpdb->get_results( $nastySQL );
foreach($results as $index => $result)
{
// Change name column to FirstName using copy and delete
$tmp = $result->name;
unset($result->name);
$result->FirstName = $tmp;
// Remove specific row
if( $result->name == "Tom")
{
unset($results[$index]);
}
}
Below code will replace the value coming from specific field of database table, if name field has value like Reo and you want to replace it with other name like John then you can to do this via below code
$results = $wpdb->get_results( $nastySQL );
foreach($results as $key => $value){
$results[$key]->name= 'John';
}
return $results;
Im some array that's being returned by some query.. and the result is something like this:
array(array('balance_1'=> '-5', 'balance_2'=>'-21'), array('balance_1'=> '-21', 'balance_2'=>'21'), array('balance_1'=> '-50', 'balance_2'=>'40'))
i want to transform this into an array that looks something like this:
array(array(-5,11,-50), array(-21, 21, 40));
basicly i want to join all balance_1, all balance_2, all balance_3 into separated arrays.
any ideas? thanks
You'll just loop over the list, then collect the values. It's most simple if you reuse the existing keys to group:
foreach ($list as $row) {
foreach ($row as $key=>$value) {
$out[$key][] = $value;
}
}
This way you'll get an $out array, with [balance_1] or [balance_2] holding the value lists.
Loop though the array and use "array_key_exists" if the key exists add to the array, if it doesn't build a new array with your index.
For more can be found here:
http://www.php.net/manual/en/function.array-key-exists.php