below is a php object which is retrieving some values from mysql db through a php method
$query = "SELECT imgpath from images";
$oMySQL->ExecuteSQL($query);
Now when i use this
$result=$oMySQL->ExecuteSQL($query);
it prints "Array"
How to iterate through the array
Regards Jane
A simple foreach loop.
foreach ($result as $key => $val) {
foreach ($val as $label => $item) {
echo $label . " - " . $item;
}
}
$key will hold the associative name the array element, and $val will hold the value of the element.
You mean it print array when you do echo $result?
Then:
foreach($result as $index => $value) {
echo $index . '=' $value;
}
Related
I'm trying out the following code for arrays in php, I create a associate array, print out the values and add one more to the array - print out again. This works, but if I try the foreach ($MovieCollection as $key => $value) it does not print out the values. Why does it not do that?
$myArray = array("Star Wars", "The Shining");
foreach ($myArray as $val)
{
echo("Movie: " . $val ."<br>");
}
$MovieCollection = array();
$MovieCollection[] = array('title' => 'Star Wars', 'description' =>'classic');
foreach ($MovieCollection as $film )
{
echo($film['title'] .": " . $film['description'] ."<br>");
}
$MovieCollection[] = array('title' => 'The shinning', 'description' =>'creepy');
foreach ($MovieCollection as $film )
{
echo($film['title'] .": " . $film['description'] ."<br>");
}
echo("<br><br>");
// This does not print the values?
foreach ($MovieCollection as $key => $value)
{
echo($key .": " . $value ."<br>");
}
That is because in this part $MovieCollection is an array of arrays and if you want to echo the $value which is an array, you will do an Array to string conversion which does not work.
What you might do is use another foreach to show the values per array:
foreach ($MovieCollection as $value) {
foreach ($value as $k => $v) {
echo($k .": " . $v ."<br>");
}
}
See a Php demo
Below is a simple array that I created:
$colors = array(
"parent1" =>array(
"item1"=>"red",
"item2"=>"green",
"item3"=>"blue",
"item4"=>"yellow"
),
"parent2" =>array(
"item1"=>"red",
"item2"=>"green",
"item3"=>"blue",
"item4"=>"yellow"
)
);
What I need to get is the key of my level 1 arrays which are string "parent1" and "parent2".
Currently I'm using foreach with while loop to get the key
foreach ($colors as $valuep) {
while (list($key, $value) = each($colors)) {
echo "$key<br />";
}
}
but I'm only able to get the "parent2" string from using the above method and not "parent1".
You're so close.
foreah($colors as $key => $val)
{
echo $key . "<br/>";
}
Use the key like so:
foreach ($colors as $key => $value) {
echo $key.'<br>';
}
To print out the keys:
foreach ($colors as $key => $value) {
echo $key . '<br />';
}
You can also get all of the keys from an array by using the array_keys() method, for example:
$keys = array_keys($colors);
foreach ($keys as $key) {
echo $key . '<br />';
}
$query2 = "SELECT * FROM `Listing` WHERE listingid = '{$myID}'";
if(!($result2 = # mysql_query($query2,$connection)))
echo "query failed<br>";
$result_array = array();
while($row2 = mysql_fetch_assoc($result2))
{
$result_array[] = $row2;
}
foreach ($result_array as $key => $val) {
echo "$key = $val\n";
}
Listing (Table) has 7 fields.
I get a bunch of "0 = Array"
How do I store mysql query results into php array and display them?
I want to have it as array first so i can sort them.
You are actually storing them. The code you have listed is storing them in array of arrays to see them you can modify the for with:
foreach ($result_array as $key => $val) {
echo "$key = " . print_r($val, true) . "\n";
}
$val is actually an array containing all the fields of a row.
I have this array:
$json = json_decode('
{"entries":[
{"id": "29","name":"John", "age":"36"},
{"id": "30","name":"Jack", "age":"23"}
]}
');
and I am looking for a PHP "for each" loop that would retrieve the key names under entries, i.e.:
id
name
age
How can I do this?
Try it
foreach($json->entries as $row) {
foreach($row as $key => $val) {
echo $key . ': ' . $val;
echo '<br>';
}
}
In the $key you shall get the key names and in the val you shal get the values
You could do something like this:
foreach($json->entries as $record){
echo $record->id;
echo $record->name;
echo $record->age;
}
If you pass true as the value for the second parameter in the json_decode function, you'll be able to use the decoded value as an array.
I was not satisfied with other answers so I add my own. I believe the most general approach is:
$array = get_object_vars($json->entries[0]);
foreach($array as $key => $value) {
echo $key . "<br>";
}
where I used entries[0] because you assume that all the elements of the entries array have the same keys.
Have a look at the official documentation for key: http://php.net/manual/en/function.key.php
You could try getting the properties of the object using get_object_vars:
$keys = array();
foreach($json->entries as $entry)
$keys += array_keys(get_object_vars($entry));
print_r($keys);
foreach($json->entries[0] AS $key => $name) {
echo $key;
}
$column_name =[];
foreach($data as $i){
foreach($i as $key => $i){
array_push($column_name, $key);
}
break;
}
Alternative answer using arrays rather than objects - passing true to json_decode will return an array.
$json = '{"entries":[{"id": "29","name":"John", "age":"36"},{"id": "30","name":"Jack", "age":"23"}]}';
$data = json_decode($json, true);
$entries = $data['entries'];
foreach ($entries as $entry) {
$id = $entry['id'];
$name = $entry['name'];
$age = $entry['age'];
printf('%s (ID %d) is %d years old'.PHP_EOL, $name, $id, $age);
}
Tested at https://www.tehplayground.com/17zKeQcNUbFwuRjC
I have a POST in PHP for which I won't always know the names of the variable fields I will be processing.
I have a function that will loop through the values (however I would also like to capture the variable name that goes with it.)
foreach ($_POST as $entry)
{
print $entry . "<br>";
}
Once I figure out how to grab the variable names, I also need to figure out how I can make the function smart enough to detect and loop through arrays for a variable if they are present (i.e. if I have some checkbox values.)
If you just want to print the entire $_POST array to verify your data is being sent correctly, use print_r:
print_r($_POST);
To recursively print the contents of an array:
printArray($_POST);
function printArray($array){
foreach ($array as $key => $value){
echo "$key => $value";
if(is_array($value)){ //If $value is an array, print it as well!
printArray($value);
}
}
}
Apply some padding to nested arrays:
printArray($_POST);
/*
* $pad='' gives $pad a default value, meaning we don't have
* to pass printArray a value for it if we don't want to if we're
* happy with the given default value (no padding)
*/
function printArray($array, $pad=''){
foreach ($array as $key => $value){
echo $pad . "$key => $value";
if(is_array($value)){
printArray($value, $pad.' ');
}
}
}
is_array returns true if the given variable is an array.
You can also use array_keys which will return all the string names.
You can have the foreach loop show the index along with the value:
foreach ($_POST as $key => $entry)
{
print $key . ": " . $entry . "<br>";
}
As to the array checking, use the is_array() function:
foreach ($_POST as $key => $entry)
{
if (is_array($entry)) {
foreach($entry as $value) {
print $key . ": " . $value . "<br>";
}
} else {
print $key . ": " . $entry . "<br>";
}
}
It's much better to use:
if (${'_'.$_SERVER['REQUEST_METHOD']}) {
$kv = array();
foreach (${'_'.$_SERVER['REQUEST_METHOD']} as $key => $value) {
$kv[] = "$key=$value";
}
}
If you want to detect array fields use a code like this:
foreach ($_POST as $key => $entry)
{
if (is_array($entry)){
print $key . ": " . implode(',',$entry) . "<br>";
}
else {
print $key . ": " . $entry . "<br>";
}
}