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.
Related
I need to create a CRON job that are weekly going to read a XML file. The XML file contains information about all the shows at a range of cinemas.
What I want to do is to read the XML file, extract the information I need about each show, and then upload each show to a database. But I run into trouble when I start nesting the for-loops.
I want each tuple to contain the following information:
Tile | FilmWebNr | Rating | Version | Center | Screen | Date | Time |
The URL for the XML is http://217.144.251.113/static/Shows_FilmWeb.php
Here is a pastebin where I try to list all the dates for each screen per Title.
Here is the result. As you can see, the dates is only displayed when there are more than 1 screen per Title. I dont get why the attributes array isn't always available.
I struggle with getting the last three (screen, date and time).
$map_url = "http://217.144.251.113/static/Shows_FilmWeb.php";
$response_xml_data = file_get_contents($map_url);
$data = simplexml_load_string($response_xml_data);
$array = (array) simplexml_load_string($response_xml_data);
$json = json_encode($array);
$configData = json_decode($json, true);
$movies = $configData['Performances']['Title'];
foreach ($movies as $title) {
echo "Title: " . $title['#attributes']['Name'] . '<br/>';
echo "FilmWebNr: " . $title['FilmWebNum'] . '<br/>';
echo "Rating: " . $title['TitleRating'] . '<br/>';
echo "Version: " . $title['TitleVersion'] . '<br/>';
echo "Center: " . $title['Center']['#attributes']['Name'] . '<br/>';
foreach ($title['Center']['Screen'] as $screen) {
//here I run into trouble
}
}
Let say I try to add the following in the inner loop:
$screen['#attributes']['Name'];
I get an error saying "Undefined index: #attributes".
So sometimes the attributes seems to be in an array, but sometimes not. Even though It is always a part of the XML.
Rather than going from XML-JSON-Arrays, it may be better to learn how to work with SimpleXML and you will find it's quite easy.
The main thing is to get used to how the various elements are layered and use foreach loops to iterate over the blocks...
$map_url = "http://217.144.251.113/static/Shows_FilmWeb.php";
$response_xml_data = file_get_contents($map_url);
$data = simplexml_load_string($response_xml_data);
$movies = $data->Performances->Title;
foreach ($movies as $title) {
echo "Title: " . $title['Name'] . '<br/>';
echo "FilmWebNr: " . $title->FilmWebNum . '<br/>';
echo "Rating: " . $title->TitleRating . '<br/>';
echo "Version: " . $title->TitleVersion . '<br/>';
echo "Center: " . $title->Center['Name'] . '<br/>';
foreach ($title->Center->Screen as $screen) {
echo "screen:".$screen['Name']. '<br/>';
foreach ( $screen->Date as $date ) {
echo "Date:".$date['Name']. '<br/>';
foreach ( $date->ShowID as $showID ) {
echo "Time:".$showID->Time. '<br/>';
}
}
}
}
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/>";
}
}
I use this code to retrieve all the post request (refer below)
<?php
foreach ($_POST as $key => $value) {
$body .= $key . ": " . $value . '<br>';
}
echo $body;
?>
and there is a post data named "adminemail" and "cat", now what i want is to eliminate those two and print all the post data except those two. How to do that? any suggestions, recommendations and ideas, would love to hear. Thank you in advance.
option 1
unset($_POST['adminemail'],$_POST['cat']);
option 2
<?php
foreach ($_POST as $key => $value) {
if(!in_array($key,array('adminemail','cat'))){
$body .= $key . ": " . $value . '<br>';
}
}
echo $body;
?>
The following should work:
<?php
$arr = array_diff_key($_POST, array("adminemail" => 0, "cat" => 0));
$body = ""; // You must have this line, or PHP will throw an "Undefined variable" notice
foreach($arr as $key => $value){
$body .= $key . ": " . $value . "<br/>";
}
echo $body;
?>
I created a foreach loop in PHP like this:
foreach( $value as $element_content => $content ) {
$canvas_elements = "<div id='" . $element_id . "'>" . $content . "</div>";
$elements[] = $canvas_elements;
}
So I get the values in a PHP array like this:
print_r($elements);
But this gives the results:
Array ( [0] =>
Text to edit
[1] =>
Text to edit
)
But I only want this output and not Array ( [0] => etc:
<div id="element_id1"></div>
<div id="element_id2"></div>
How is this done?
Why bother with the array, if you want nothing but echo/print out some markup:
foreach( $value as $element_content => $content )
{
echo "<div id='" . $element_id . "'>" . $content . "</div>";
}
Whill do, however, if you insist on using that array:
echo implode('', $elements);
turns the array into a string, just like you wanted it to. Your using print_r is not the way forward, as it's more of a debug function: check the docs
Prints human-readable information about a variable
Just a little detail: you don't seem to be declaring $elements as an array anywhere. PHP will create a new variable, and assign it an empty array for you, true enough, but if you change your ini settings to E_STRICT | E_ALL, you'll notice that it doesn't do this without complaining about it. (and rrightfully so)
It's always better to declare and initialize your variables beforehand. writing $elements = array(); isn't hard, nor is it very costly. At any rate it's less costly than producing a notice.
use like this
<?php
$data = array('a'=>'apple','b'=>'banana','c'=>'orange');
$string = implode("<br/>", $data);
?>
<pre><?php print_r($string); ?></pre>
OUTPUT
apple
banana
orange
print_r($array) is a function to display the value of the variable to the user. it's created for debugging purposes. If you want to have a HTML output, please use "echo" or something particular.
foreach( $value as $element_content => $content ) {
echo "<div id='" . $element_id . "'>" . $content . "</div> \n";
}
$elements = array();
foreach( $value as $element_content => $content ) {
$canvas_elements = "<div id='" . $element_id . "'>" . $content . "</div>";
$elements[] = $canvas_elements;
}
echo $mergedStrArray = implode("\n", $elements);
Can you try for me, Does it work?
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) {...