Is there something wrong with this foreach code? - php

foreach ($data['tests'] as $testname => $tests) {
echo "<h1>Extraction $testname Tests</h1>\n";
$function = $testfunctions[$testname];
echo "<ul>";
foreach ($tests as $test) {
echo "<li>" . $test['description'] . ' ... ';
$extracted = $extractor->$function($test['text']);
if ($test['expected'] == $extracted) {
echo " <span style='color: green'>passed.</span></li>";
} else {
echo " <span style='color: red'>failed.</span>";
echo "<pre>Original: " . htmlspecialchars($test['text']) . "\nExpected: " . print_r($test['expected'], true) . "\nActual : " . print_r($extracted, true) . "</pre>";
}
echo "</li>";
}
echo "</ul>";}
I keep getting the error:
Warning: Invalid argument supplied for
foreach() in
C:\xampp\htdocs\test\runtests.php on
line 49
p.s. the beginning of the code is line 49, so the probelm starts with the foreach statment.

Whenever i see that, it tends to mean that the thing i'm trying to iterate through isn't an array.
Check $data['tests'] (and each inner $tests) to make sure it's not null/unset/empty, and that it's something iterable like an array. Also keep in mind that older versions of PHP (before 5.0?) don't do iterable objects very well.

One of the elements in $data["tests"] is probably not an array.
Add this before the foreach:
if (is_array($tests))
foreach ($tests as $test) {...

Related

Loop through associative array and assign values

I have an array:
$instructions = array (
array("step_no"=>"1","description"=>"Ensure that you have sufficient balance"),
array("step_no"=>"2","description"=>"Approve the request sent to your phone")
);
What I want is to loop through this array, which I have done, but I am now confused because I don't know how to get the output I desire.
foreach ($array as $key => $value) {
//echo $key . "\n";
foreach ($value as $sub_key => $sub_val) {
if (is_array($sub_val)) {
//echo $sub_key . " : \n";
foreach ($sub_val as $k => $v) {
echo "\t" .$k . " = " . $v . "\n";
}
} else {
echo $sub_key . " = " . $sub_val . "\n";
}
}
}
The above code loops through the array, but this line of code:
echo $sub_key . " = " . $sub_val . "\n";
gives me:
step_no = 1 description = Ensure that you have sufficient balance step_no = 2 description = Approve the request sent to your phone
when I change it to:
echo $sub_val . "\n";
it gives me:
1 Ensure that you have sufficient balance 2 Approve the request sent to your phone
But I what I truly want is:
1. Ensure that you have sufficient balance
2. Approve the request sent to your phone
Is this possible at all? Thanks.
$instructions = array (
array("step_no"=>"1","description"=>"Ensure that you have sufficient balance"),
array("step_no"=>"2","description"=>"Approve the request sent to your phone")
);
foreach($instructions as $instruction) {
echo $instruction['step_no'] . '. ' . $instruction['description'] . "\n";
}
If it's HTML you may want to use <ol> and <li>.
It smells like you are not running this script in command line but in browser. If so, then \n makes no visual effect (unless within <pre> block) and you u must use HTML tag <br /> instead. Also, drop concatenation madness and use variable substitution:
echo "{$sub_key}. = {$sub_val}<br/>";
You can simple achieve this way
<?php
$instructions = array (
array("step_no"=>"1","description"=>"Ensure that you have sufficient balance"),
array("step_no"=>"2","description"=>"Approve the request sent to your phone")
);
foreach($instructions as $instruction){
echo $instruction['step_no'].'. '.$instruction['description'].PHP_EOL;
}
?>
Alway keep it simple.

PHP Json values with a specified label

I am using json_decode and echoing the values using a nested foreach loop.
Here's a truncated json that I am working on:
[{"product_name":"Product 1","product_quantity":"1","product_price":"2.99"},....
and the loop
foreach($list_array as $p){
foreach($p as $key=>$value) {
$result_html .= $key.": ".$value."<br />";
}
}
This was I am able to echo all key/value pairs.
I have tried using this to echo individual items something like:
foreach($list_array as $p){
foreach($p as $key=>$value) {
echo "Product: ".$p[$key]['product_name'];
echo "Quantity: ".$p[$key]['product_quantity'];
}
}
However I am unable to because it doesn't echo anything.
I would like to be able to show something like:
Product Name: Apple
Quantity: 7
Currently it is showing:
product_name: Apple
product_quantity: 7
How can I remove the key and replace it with a predefined label.
It can be done with:
foreach ($list_array as $p){
$result_html .= 'Product: ' . $p->product_name
. 'Quantity: ' . $p->product_quantity . '<br />';
}
If you are decoding your json into an object you can do it like that.
$list_array = json_decode('[{"product_name":"Product 1","product_quantity":"1","product_price":"2.99"}]');
$result_html = '';
foreach($list_array as $p){
$result_html .= '<div>Product: '.$p->product_name.'</div>';
$result_html .= '<div>Quantity: '.$p->product_quantity.'</div>';
}
echo $result_html;

Parsing a JSON string with multiple arrays

I am trying to parse this JSON string
$json = {"fields":{
"relationshipStatus":[{"fieldId":4,"name":"Committed"},{"fieldId":2,"name":"Dating"},{"fieldId":6,"name":"Engaged"},{"fieldId":3,"name":"Exclusive"},{"fieldId":7,"name":"Married"},{"fieldId":8,"name":"Open Relationship"},{"fieldId":5,"name":"Partnered"},{"fieldId":1,"name":"Single"}],
"ethnicity":[{"fieldId":1,"name":"Asian"},{"fieldId":2,"name":"Black"},{"fieldId":3,"name":"Latino"},{"fieldId":4,"name":"Middle Eastern"},{"fieldId":5,"name":"Mixed"},{"fieldId":6,"name":"Native American"},{"fieldId":8,"name":"Other"},{"fieldId":9,"name":"South Asian"},{"fieldId":7,"name":"White"}],
}}
Using this foreach loop, ultimately I want to be able to take the data and use them as Select / List dropdowns on a form.
foreach($json['fields'] as $item){
foreach($item['relationshipStatus'] as $relationship){
echo $relationship['name'] . " " . $relationship['fieldId'] . "<br/>";
}
foreach($item['ethnicity'] as $ethnicity){
echo $ethnicity['name'] . " " . $ethnicity['fieldId'] . "<br/>";
}
}
No matter how I try to pull the data out, I keep getting errors similar to:
Notice: Undefined index: relationshipStatus in
/Applications/MAMP/htdocs/updateprofile.php on line 126 Warning:
Invalid argument supplied for foreach() in
/Applications/MAMP/htdocs/updateprofile.php on line 126
What am I doing wrong?
The first foreach selects already relationshipStatus and ethnicity. Maybe the following changes show what I mean:
foreach($json['fields'] as $key=>$item){
if ($key == 'relationshipStatus')
foreach($item as $relationship){
echo $relationship['name'] . " " . $relationship['fieldId'] . "<br/>";
}
else if ($key == 'ethnicity')
foreach($item as $ethnicity){
echo $ethnicity['name'] . " " . $ethnicity['fieldId'] . "<br/>";
}
}
Here, you iterating the JSON Object in a wrong way.The array values you want to fetch is actually under $json['fields']['relationshipStatus'].
var name = $json['fields']['relationshipStatus']['name'];
var fieldId = $json['fields']['relationshipStatus']['fieldId'];
=============================== OR ========================================
As described by the A.fink
foreach($json['fields'] as $key=>$item){
if ($key == 'relationshipStatus')
foreach($item as $relationship){
echo $relationship['name'] . " " . $relationship['fieldId'] . "<br/>";
}
else if ($key == 'ethnicity')
foreach($item as $ethnicity){
echo $ethnicity['name'] . " " . $ethnicity['fieldId'] . "<br/>";
}
}

PHP Error: invalid argument supplied for foreach()

I'm trying to use this function at the bottom of a plugin's main PHP file to determine if one of its action hooks is being used by the tag specified. However, I'm getting a "Warning" on the 2nd foreach in the code below. Why is this? Is there a better way to see if a Wordpress action hook is being used?
<?php
function dump_hook($tag, $hook)
{
ksort($hook);
echo "<pre>>>>>>\t$tag<br>";
foreach ($hook as $priority => $functions) {
echo $priority;
foreach ($functions as $function) {
if ($function['function'] != 'list_hook_details') {
echo "\t";
if (is_string($function['function']))
echo $function['function'];
elseif (is_string($function['function'][0]))
echo $function['function'][0] . ' -> ' . $function['function'][1];
elseif (is_object($function['function'][0]))
echo "(object) " . get_class($function['function'][0]) . ' -> ' . $function['function'][1];
else
print_r($function);
echo ' (' . $function['accepted_args'] . ') <br>';
}
}
}
echo '</pre>';
}
$tag = array('anspress_loaded');
$hook = array('find_do_for_anspress');
dump_hook($tag, $hook);
Some errors from your code:
1.) $tag is array, but in your function it's used as string:
<?php
echo "<pre>>>>>>\t$tag<br>";
2.)$hook is array, so first foreach works ok:
<?php
// for first row
// $priority is int 0
// $functions is string find_do_for_anspress
foreach($hook as $priority => $functions ) {}
Next you try to do foreach with string $functions, but it's not iterrable, so php says to you aforementioned error.

how to print variable/array out of function

I need the array($project_Ids) out of function any suggestion.This is in view
I can't call the function cause already is called; I just want some how to update this array().
$project_Ids=array();
function generateProperties($listP, $sizeS){
global $project_Ids;
$i=0;
foreach ($listP as $pr) {
$i++;
$pr['project_id'];
$project_Ids[$i]=$pr['project_id'];
echo "<li class='' style='cursor: pointer;height:" . $sizeSmallBlock . "px;' dds='" . $project['project_id'] . '-' . $project['project_calendar_id'] . "' id='" . $project['project_id'] . '-' . $project['project_calendar_id'] . "'>" .
$description .
"</li>";
}
}
You need to define the array inside the function, and then have the function return it!
function generateProperties($listP, $sizeS){
$project_Ids=array();
$i=0;
foreach ($listP as $pr) {
$i++;
$project_Ids[$i]=$pr['project_id'];
}
return $project_Ids;
}
// then elsewhere in your code
$project_Ids = generateProperties($listP, $sizeS);
Edit:
From looking at your foreach loop - it seems you are just getting the array values and storing them in an array? If so - just use array_values - it does exactly what you want in one line of code:
$project_Ids = array_values($listP);
It is already available outside of the function, as you have correctly defined it outside.
You may want to brush up on scope.
$project_Ids = generateProperties($listP, $sizeS);
This will work but you have to read it from end of the page after rendering all the page :)

Categories