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?
Related
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.
I'm trying to do something very basic but I can't figure out how.
basically i'm trying to convert the mysql result ($row) into the following format (literal strings):
"0784562627828" => "James",
"0786636363663" => "David",
I have all the data stored in the database and I can get them echoed on my page like so:
$phone = $row['phone'];
$name = $row['name'];
$list .=''.$phone.'';
echo $list;
could someone please advise on this?
Thanks
Just assign them inside an array like you normally would:
$array = array();
while(your fetch here) {
$array[$row['phone']] = $row['name'];
}
To check its contents, you can use var_dump($array) or print_r($array)
Or just straight up show them, like the one you formatted:
while(your fetch here) {
echo '"' . $row['phone'] . '"' . ' => ' . '"' . $row['name'] . '"' . '<br/>';
}
you mean something like this?
$list = array();
$list[$phone] = $name;
Can you do something like
$list = [];
foreach($rows as $row) {
$list[$row['phone']] = $row['name'];
}
First and foremost, forgive me if my language is off - I'm still learning how to both speak and write in programming languages. How I can retrieve an entire object from an array in PHP when that array has several key, value pairs?
<?php
$quotes = array();
$quotes[0] = array(
"quote" => "This is a great quote",
"attribution" => "Benjamin Franklin"
);
$quotes[1] = array(
"quote" => "This here is a really good quote",
"attribution" => "Theodore Roosevelt"
);
function get_random_quote($quote_id, $quote) {
$output = "";
$output = '<h1>' . $quote["quote"] . '.</h1>';
$output .= '<p>' . $quote["attribution"] . '</p>';
return $output;
} ?>
<?php
foreach($quotes as $quote_id => $quote) {
echo get_random_quote($quote_id, $quote);
} ?>
Using array_rand and var_dump I'm able to view the item in the browser in raw form, but I'm unable to actually figure out how to get each element to display in HTML.
$quote = $quotes;
$random_quote = array_rand($quote);
var_dump($quote[$random_quote]);
Thanks in advance for any help!
No need for that hefty function
$random=$quotes[array_rand($quotes)];
echo $random["quote"];
echo $random["attribution"];
Also, this is useless
<?php
foreach($quotes as $quote_id => $quote) {
echo get_random_quote($quote_id, $quote);
} ?>
If you have to run a loop over all the elements then why randomize hem in the first place? This is circular. You should just run the loop as many number of times as the quotes you need in output. If you however just need all the quotes but in a random order then that can simply be done in one line.
shuffle($quotes); // this will randomize your quotes order for loop
foreach($quotes as $qoute)
{
echo $quote["quote"];
echo $quote["attribution"];
}
This will also make sure that your quotes are not repeated, whereas your own solution and the other suggestions will still repeat your quotes randomly for any reasonably sized array of quotes.
A simpler version of your function would be
function get_random_quote(&$quotes)
{
$quote=$quotes[array_rand($quotes)];
return <<<HTML
<h1>{$quote["quote"]}</h1>
<p>{$quote["attribution"]}</p>
HTML;
}
function should be like this
function get_random_quote($quote_id, $quote) {
$m = 0;
$n = sizeof($quote)-1;
$i= rand($m, $n);
$output = "";
$output = '<h1>' . $quote[$i]["quote"] . '.</h1>';
$output .= '<p>' . $quote[$i]["attribution"] . '</p>';
return $output;
}
However you are not using your first parameter-$quote_id in the function. you can remove it. and call function with single parameter that is array $quote
Why don't you try this:
$quote = $quotes;
$random_quote = array_rand($quote);
$random = $quote[$random_quote];
echo '<h1>' . $random["quote"] . '.</h1><br>';
echo '<p>' . $random["attribution"] . '</p>';
Want to create a function:
echo get_random_quote($quotes);
function get_random_quote($quotes) {
$quote = $quotes;
$random_quote = array_rand($quote);
$random = $quote[$random_quote];
return '<h1>' . $random["quote"] . '.</h1><br>'.'<p>' . $random["attribution"] . '</p>';
}
First, you dont need the $quote_id in get_random_quote(), should be like this:
function get_random_quote($quote) {
$output = "";
$output = '<h1>' . $quote["quote"] . '.</h1>';
$output .= '<p>' . $quote["attribution"] . '</p>';
return $output;
}
And I cant see anything random that the function is doing. You are just iterating through the array:
foreach($quotes as $quote_id => $quote) {
echo get_random_quote( $quote);
}
According to http://php.net/manual/en/function.array-rand.php:
array_rand() Picks one or more random entries out of an array, and
returns the key (or keys) of the random entries.
So I guess $quote[$random_quote] should return your element, you can use it like:
$random_quote = array_rand($quotes);
echo get_random_quote($quote[$random_quote]);
Want to set up a page that parse out info from a XML feed according to a give ID...
Like "Show the Course->info where Course->ID = 123"
Probably "need" to get the id from a URL Variable ... urL: ://.../courseinfo.php?id=123
This show each instance - but I want a solution that shows only info from One particual ID.
"simialr" to a sql query like "GET * where COURSE_ID=" & $urlcourseid"
$xml=simplexml_load_file("https://www.kursadmin.org/pls/kas/sf_fu.create_web_cdata_xml");
foreach($xml as $x) {
foreach($x->KURS as $y){
echo "Kursnavn: " . $y->KURS_NAVN . "<br>";
echo "KursID: " . $y->KURS_ID . "<br><br>";
echo "Formål: " . $y->FORMAL . "<br>";
//echo "Beskrivelse: <p>" . $y->INNHOLD . "</p>";
echo "<br><br> <Hr>";
}
}
Any suggestions?
As everyone's probably suggested, you should be using XPath to query this. What they're leaving out is that you have to mind the XML namespace before you can do that here. Here's a programmatic way to both mind the namespace, and to query for a specific record ID:
$xml = simplexml_load_file( "sf_fu.create_web_cdata_xml" );
$namespaces = $xml->getNamespaces( true ); # array([]="crystal-reports:schemas")
$namespace = array_shift( $namespaces ); # urn:crystal-reports:schemas
$xml->registerXPathNamespace("kurses", $namespace );
$results = $xml->xpath( "//kurses:KURS[kurses:KURS_ID=1463486771]" );
Note that my XPath query is prefixed with kurses: - that is the namespace prefix that I designated I wanted to use with the queries, that the XML file reflects (see the Report xmlns='' tag)
Anyhow, the result is an array of records, in our case length 1 since there's only one ID with that number. Printing it out looks like what you'd expect (redacted a few details):
print_r($results) = Array (
[0] => SimpleXMLElement Object (
[#attributes] => Array (
[SectionNumber] => 0
[teller] => 0
)
[KURSSERIE_ID] => SimpleXMLElement Object (
[#attributes] => Array (
[FieldName] => {ARRMENT_TBL.AM_ID}
)
)
[KURS_ID] => 1463486771
[KURS_NAVN] => Norsk litt øvet (A2) - Eid
[KLSTART] => 1730
Given that the record ID # is an integer, you should be able to cheaply sanitize it by doing something like:
$KURS_ID = intval( $_GET['KURS_ID'] );
...
$results = $xml->xpath( "//kurses:KURS[kurses:KURS_ID={$KURS_ID}]" );
the obvious way:
foreach($xml as $x) {
foreach($x->KURS as $y){
if( $y->KURS_ID == $_GET['id']){
echo "Kursnavn: " . $y->KURS_NAVN . "<br>";
echo "KursID: " . $y->KURS_ID . "<br><br>";
echo "Formål: " . $y->FORMAL . "<br>";
//echo "Beskrivelse: <p>" . $y->INNHOLD . "</p>";
echo "<br><br> <Hr>";
}
}
}
I'm using PHPQuery to read some content from HTML, I'm unable to get the element by it's index using the square bracket notation.
See this simple example:
$html = '<div><table id="theTable"><tr><td>FIRST TD</td><td>SECOND TD</td><td>THIRD TD</td></tr></table></div>';
$pq = phpQuery::newDocumentHTML($html);
$table = $pq->find('#theTable');
$tds = $table->find('td');
echo "GETTING BY INDEX:\n\n";
echo '$tds[1] = ' . $tds[1];
echo "\n\n\n";
echo "GETTING IN FOREACH:\n\n";
foreach($tds as $key => $td){
echo '$tds[' . $key . '] = ' . pq($td) . "\n";
}
The output of this is:
GETTING BY INDEX:
$tds[1] =
GETTING IN FOREACH:
$tds[0] = FIRST TD
$tds[1] = SECOND TD
$tds[2] = THIRD TD
I would have expected that I can get the contents of $tds[1] using square brackets, but seems not. How can I get it by index?
Try a var_dump($tds), it'll tell you whats exactly inside the tds. Maybe those keys are actually strings and you should use:
echo "GETTING BY INDEX:\n\n";
echo '$tds['1'] = ' . $tds['1'];
Edit: Also, on your foreach you're using pq(), maybe you should use this
echo "GETTING BY INDEX:\n\n";
echo '$tds[1] = ' . pq($tds[1]);
Found the answer just after posting the question. Instead of square brackets you need to use eq(n):
echo '$tds[1] = ' . $tds->eq(1);
Try the following:
echo '$tds[1] = ' . $tds['1'];