Getting a random object from an array in PHP - php

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]);

Related

PHP - Use variable names with numbers through a loop

In my for loop for ($i = 1; $i <= 3; $i++) i have have html code that will be echod 3 times. The html also using PHP objects ($help).
$help has 3 things, $help->url_1, $help->text_1, $help->icon_1. But through the loop, I want it so that when for example $i is at 2, i want to use $help->url_2, etc. How can i sort of increment the variable name in the echo string of in the loop?
<?php
class Help
{
public $url;
public $text;
public $icon;
}
$help1 = new Help();
$help1->url = 'your url';
$help1->text = 'your text';
$help1->icon = 'url to your icon';
$helps[] = $help1;
//Repeat for other helps (help2, help3, etc.)
?>
Once you have an array of objects, you only need to loop into it using a foreach loop :
foreach ($helps as $help) {
echo "<h3>" . $help->url . "</h3>";
echo "<p>" . $help->text . "</p>";
echo "<img src='" . $help->icon . "' alt='your alt'/>";
}

Trying to find a way to take a series of values in a json array and add them to an int

Here is my PHP function that grabs data from inputs on the page.
function getCounts($selection, $srch) {
$loadjson = file_get_contents('data.json');
$jsondata = json_decode($loadjson);
$total = 0;
foreach ($jsondata as $list) {
if ($list->$selection == $srch) {
$total .= $list->TOTAL
}
}
echo 'Total - ' . $total . '<br>' . '<br>';
}
I know the issue is with the line "$total .= $list->TOTAL" but I cannot figure out how to take the value that "$list->TOTAL" gets and add it to an integer. I have tested and if I do "echo $list->TOTAL . ','" instead of "$total .= $list->TOTAL" the function spits out a list of all the numbers that are in the JSON data I simply cannot figure out how to get the numbers into an integr and added into one number.
Can someone point me in the right direction?

Auto increment through a php loop

I have a case where I am using the code below to populate a template of sorts. Within the templates' javascript I would individually check the data attribute field I setup, essentially causing me to have multiple JS files instead of one that is shared. I then thought I could use a generic name field too, but prepend a number through the loop.
For example, with the line of code below where the `name="testField". I want to see if there is a way that I can add a number, but auto increment it through the loop with php.
Is this possible?
echo '<div class="markerItem" name="testField' . $number . '" "data-marker="' . $marker_data . '">';
PHP Code
if ($marker_stmt = $con->prepare($sql_marker)) {
$marker_stmt->execute();
$marker_rows = $marker_stmt->fetchAll(PDO::FETCH_ASSOC);
echo '<div id="projMarker">';
foreach ($marker_rows as $marker_row) {
$marker_solution = $marker_row['solution'];
$maker_item = $marker_row['subSolution'];
$marker_data = $marker_row['subSolution'];
echo '<div class="markerItem" data-marker="' . $marker_data . '">';
echo $marker_item;
echo '</div>';
}
}
echo '</div>';
if ($marker_stmt = $con->prepare($sql_marker)) {
$marker_stmt->execute();
$marker_rows = $marker_stmt->fetchAll(PDO::FETCH_ASSOC);
echo '<div id="projMarker">';
foreach ($marker_rows as $key=>$marker_row) {
$marker_solution = $marker_row['solution'];
$maker_item = $marker_row['subSolution'];
$marker_data = $marker_row['subSolution'];
echo '<div class="markerItem" name="testField_'.$key.'" data-marker="' . $marker_data . '">';
echo $marker_item;
echo '</div>';
}
}
echo '</div>';
Using this, $key is assigned from the array index which will be a number starting from 0 and ending at count($marker_rows)-1.
Suprisingly, I couldn't find an appropriate duplicate for this.
You can easily increment or decrement variables in PHP.
$number = 0;
foreach ($marker_rows as $marker_row) {
...
$number++; // $number will now be $number+1
}
You can use $number++ directly in your attribute (if concatenating) as this will return the current $number then increment the value.

PHP array_push() 2-dimensional array

array_push($typedict[$current], "value");
Does not seem to do anything here, i output the associative array of arrays($typedict) but all of them are empty(array()). I print the current associative index out with echo to confirm that it is the correct one(it always is).
Since the print chelc at the end states "[name] => Array()" i have no clue what could be the problem as this indicates that they are indeed arrays and therefore could have stuff pushed in. Also the var $current as stated always have the correct content. at:
echo "current: ". $current;
full code:
<?php
$typedict = array();
$xsdstring = file_get_contents("infile.xsd");
$xsdstring = str_replace("xs:choice", "xs:sequence", $xsdstring);
$doc = new DOMDocument();
$doc->loadXML(mb_convert_encoding($xsdstring, 'utf-8', mb_detect_encoding($xsdstring)));
$xpath = new DOMXPath($doc);
$xpath->registerNamespace('xs', 'http://www.w3.org/2001/XMLSchema');
$xpath->registerNamespace('vc', 'http://www.w3.org/2007/XMLSchema-versioning');
function outputFormat($indent, $elementDef)
{
echo "<div>" . $indent . $elementDef->getAttribute('name')
. " type:" . $elementDef->getAttribute('type')
. " min:" . $elementDef->getAttribute('minOccurs')
. " max:" . $elementDef->getAttribute('maxOccurs')
. "</div>\n";
}
function echoElements($indent = "", $elementDef, $evaluate, &$typedict)
{
global $doc, $xpath, $current;
if($indent == "")
{
$attribute_name = $elementDef->getAttribute('name');
$typedict[$attribute_name] = array();
$current = $attribute_name;
}else{
echo "current: ". $current;
$type = $elementDef->getAttribute('name');
array_push($typedict[$current], "value");
#$typedict[$current][0] = "value";
print_r($typedict[$current]);
}
outputFormat($indent, $elementDef);
$elementDefs = $xpath->evaluate($evaluate, $elementDef);
foreach($elementDefs as $elementDef)
{
echoElements($indent . " ", $elementDef, $evaluate);
}
}
$elementDefs = $xpath->evaluate("/xs:schema/xs:element");
foreach($elementDefs as $elementDef)
{
echoElements("", $elementDef, "xs:complexType/xs:sequence/xs:element", $typedict);
}
$elementDefs = $xpath->evaluate("/xs:schema/xs:complexType");
foreach($elementDefs as $elementDef)
{
echoElements("", $elementDef, "xs:sequence/xs:element", $typedict);
}
print_r($typedict);
?>
$current does contain the correct value. As seen in the code i check it pretty much everytime it gets set. So im pretty confident about that part.
I do not want to change whatever is in $current as it behaves excactly as i want.
My goal is an array inside each entry of the associative array $typedict.
Example:
$typedict["whatever"][0] = "value";
$typedict["whatever"][1] = "value";
...
$current is the index of $typedict not any of it's contents. So in this case $current contains the string "whatever" and not "value". And this is how it should be.
Edit:
I think i figured out the problem. But i have no clue how this could happen and therefore can't fix it:
$typedict["whatever"] seems to be only visible inside the IF block since the last value is okay if chekcked inside the block.
I somehow need to declare the whole structure of $typedict as global. Not just the base array(the associative one) but alos all the arrays inside it. But i only get to know the keys later.
Edit2:
Definetly a visibilty problem:
changing:
global $doc, $xpath, $current;
to:
global $doc, $xpath, $current, $typedict;
solved it

Get values from PHP array

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?

Categories