I have a xml file that i want to echo to the browser
echo $rule = $info->rule1
echo $rule = $info->rule2
Result:
example 1
example 2
Because the rule in the xml is dynamic i want to count how much rules there are and pass that variable behind the "rule"
$xml = simplexml_load_file('file.xml');
$xml_nested = $xml->monthlegenda;
echo "<ul>";
foreach ($xml_nested as $info):
for($i=1; $i < count($info); $i++){
$rule = $info->rule;
$rule .= $i;
echo $rule;
};
endforeach;
echo "</ul>";
As a result i expect:
example 1
example 2
but i get
12
You're probably looking for a way to get the property of an object from a string, which is done like so:
$instance->{$var.'string-part'.$otherVar};
In your case, that'd be:
echo $info->{'rule'.$i};
For more details, refer to the man pages on variable variables. Especially the section entitled " #1 Variable property" should be of interest to you...
But since you're echoing <ul> tags before and after the loop, I'm assuming you're trying to create a list, in which case, your echo statement should look like this:
echo '<li>', $info->{'rule'.$i}, '</li>';//comma's not dots!
Note that you'll never loop through the entire $info object, because of your for loop. You should either write:
for ($i=1,$j = count($info);$i<=$j;$i++)
{
echo $info->{'rule'.$i};
}
Note that I'm assigning count($info) to a variable, to avoid calling count on each iteration of the loop. You're not changing the object, so the count value will be constant anyway... or simply use foreach:
foreach($info as $property => $val)
{//val is probably still an object, so use this:
echo $info->{$property};
}
In the last case, you could omit the curlies around $property, but that's not recommended, but what you can do here, is check if the property concerned is a rule property:
foreach($info as $property => $val)
{
if (substr($property, 0, 4) === 'rule')
{//optionally strtolower(substr($property, 0, 4))
echo '<li>', $info->{$property}, '<li>';
}
}
That's the easiest way of doing what you're doing, given the information you've provided...
Try this code for "for":
for($i=1; $i < count($info); $i++)
{
$rule = $info->{'rule'.$i};
echo $rule;
}
Try this one:
$rule = $info->{rule.$i};
Check this
$xml = simplexml_load_file('file.xml');
$xml_nested = $xml->monthlegenda;
echo "<ul>";
foreach ($xml_nested as $info)
for($i=1; $i < count($info); $i++){
$rule = "";
$rule = $info->rule;
$rules = $rule.$i;
echo $rules;
}
echo "</ul>";
Related
Hello I am submitting a form with POST method and I want its contents to be echo'ed one by one apart from the last one. So far I am using
<?php foreach($_POST as $data){
echo $data;
}
?>
which displays the whole array of $_POST, how can I make it using common "for" loop to not echo the last item of the array? It doesnt seem to work
<?php
$length=count($_POST)-1;
for($i=0; $i<$length; $i++) {
echo $_POST[$i];
?>
<br>
<?php } ?>
I am getting 5 errors, undefined offset 0 through 4 where the echo line is present
Do the following:
<?php
$counter = 0;
$lastItemOrder = count($_POST);
foreach($_POST as $value) {
$counter++;
if( $counter !== $lastItemOrder) {
echo $value;
}?>
<br><?php
} ?>
Your loop for just get numerical index like $_POSR[0], $_POST[1]... This just would work if in the HTML the attribute name of the input elements be numerical also, like name="0" and so on.
foreach perform loop on array independently of index, numerical or string.
Try this:
<?php
$counter = 0;
$lastItemOrder = count($_POST);
foreach($_POST as $index => $value) {
$counter++;
if( $counter !== $lastItemOrder) {
echo $index . ": " . $value;
}?>
<br><?php
} ?>
ok now I get it, I didnt know the difference between associative and numeric arrays. I fixed it with an if statement
My Script :
<?php
$values='Product1,54,3,888888l,Product2,54,3,888888l,';
$exp_string=explode(",",$values);
$f=0;
foreach($exp_string as $exp_strings)
{
echo "".$f." - ".$exp_string[$f]." ";
if ($f%3==0)
{
print "<br><hr><br>";
}
$f++;
}
?>
With this code i want show data inside loop, the idea it´s show all information in groups the elements in each group it´s 4 elements and must show as this :
Results :
Group 1 :
Product1,54€,3,green
Group 2:
Product2,56€,12,red
The problem it´s i don´t know why, don´t show as i want, and for example show separate some elements and not in group, thank´s , regards
It looks like you are trying to combine elements of a for loop and a foreach loop.
Here is an example of each, pulled from the php manual:
For Loop
for($index = 0, $index < size($array), $index++ {
//Run Code
//retrieve elements from $array with $array[$index]
}
Foreach
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
It's hard for me to understand what your input looks like. If you post an example of $exp_strings, I could be of better assistance. But from the sound of your question, if $exp_strings is multidimensional if you need to loop through groups of items, you could try nesting one loop inside another loop like so:
$groups_of_data = array(array(...), array(...), array(...));
for($i = 0, $i < size($groups_of_data), $i++) {
$group = $i;
for($j = 0, $j < size($groups_of_data[$i]), $j++) {
// print out data related to group $i
}
}
This is really all guesswork on my part though as I can't see what your input string/array is. Can you post that? Maybe I can be of more help.
here is code i worked out. it was kind of since i did't know what object $exp_string is. if it's a string you should tokenize it, but i think it's array from database. there was another problem, with your code where it tries to output $exp_string[$f] it should be $exp_strings what changes in the loop.
my code
$exp_string=array("Product"=>54,"price"=>3,"color"=>"green");
$f=0;
foreach($exp_string as $key => $exp_strings)
{
if($f%3==0)
{
print "<br><hr><br>";
echo "Product ".$exp_strings."<br> ";
}
else if($f%3==1)
{
echo "Price ".$exp_strings."<br> ";
}
else if($f%3==2)
{
echo "Color ".$exp_strings."<br> ";
}
$f++;
}
hope it's any help, maybe not what you wanted.
$values='Product1,1,2,3,Product2,1,2,3,Product3,1,2,3';
$products = (function($values) {
$exp_string = explode(',', $values);
$products = [];
for ($i=0; $i+3<count($exp_string); $i+=4) {
$product = [
'title' => $exp_string[$i],
'price' => $exp_string[$i+1],
'color' => $exp_string[$i+2],
'num' => $exp_string[$i+3],
];
array_push($products, $product);
}
return $products;
})($values);
/* var_dump($products); */
foreach($products as $product) {
echo "{$product['title']},{$product['price']},{$product['color']},{$product['num']}<br>";
}
Following my unsolved question,
I'm trying to figure how to use foreach
How can I make this kind of code:
$m1="mbob";
$m2="mdan";
$m3="mbill";
$a = array('bob', 'dan', 'bill');
$i = 1; /* for illustrative purposes only */
foreach ($a as $v) {
echo "\$a[$i] => $v.\n";
echo $m[$i];
$i++;
}
To output this result:
$a[1] => bob.
mbob
$a[2] => dan.
mdan
$a[3] => bill.
mbill
I'm getting the error:
Undefined variable: m
But I'm trying to output the m1,m2,m3 variables, not just m.
That's something I've never done but you may try and give it a shot:
echo $('m' . $i);
That's similar to function invocations where you construct the function name dynamically through a string, but I don't know if it works with local variables as well.
Here is code that works, but I would not recommend it. I would recommend just storing your $m values in an array.
<?php
$m1="mbob";
$m2="mdan";
$m3="mbill";
$array = array('bob', 'dan', 'bill');
$i = 1;
foreach ($array as $value) {
echo "\$a[$i] => $value.\n";
echo '<br>';
echo ${"m".$i};
echo '<br>';
$i++;
}
?>
In your code, $m is not an array. There is a way to create variable variable names which appears to be what you are trying to do, but simpler is to create $m as an array:
$m =array("mbob","mdan","mbill");
$a = array('bob', 'dan', 'bill');
$i = 1; /* for illustrative purposes only */
foreach ($a as $v) {
echo "\$a[$i] => $v.\n";
echo $m[$i];
$i++;
}
After searching for an answer in this forum I found only related questions but under other context that would not apply to my case. Here's my problem:
I have a 3-dim array defined in a function like this:
$m_Array[h][$family][$iterator]
the values for
$family range from 6-10;
$iterator from 0-3 but has duplicates (0,1,2,3,1),
and the $m_Array results in values (25,26,30,31,33).
I am unable to echo the result using those indices to get these results once returned from the function.
NOTE: I was able to echo when I had 2-dim $m_Array[h][$iterator] but could not use it because the last value for the iterator would replace the second in the array.
Since I was able to echo the 2-dim, this is not a question on getting the return from the function or iterate over the indices.
Thanks.
Use print_r($arrayName) to print an array. You cannot echo an Array or Object
as others mentioned, you can use var_dump() or print_r(). If you need to access each item then you're going to need nested loops.
foreach($m_Array as $i => $h)
{
//echo $i, $key for h
foreach($h as $j => $family)
{
//echo $j, key for family
foreach($family as $k => $iterator)
{
echo $iterator;
}
}
}
try this:
$keys = array_keys($h);
for($i = 0; $i < count($h); $i++) {
echo $keys[$i] . "{<br>";
foreach($h[$keys[$i]] as $key => $value) {
echo $key . " : " . $value . "<br>";
}
echo "}<br>";
}
It prints all values and keys
Following function arranges the array totally wrong. Have you noticed any wrong piece of code in following function?
function buildHtmlList($array)
{
$maxlevel = 0;
foreach ($array as $key => $value)
{
$previousparent = isset($array[$key - 1]['parent']) ? $array[$key - 1]['parent'] : null;
$nextparent = isset($array[$key + 1]['parent']) ? $array[$key + 1]['parent'] : null;
if ($value['parent'] != $previousparent)
{
echo "\n<ul>";
++$maxlevel;
}
echo "\n<li>" . $value['name'];
if ($nextparent == $value['parent'])
echo "</li>";
}
for ($i = 0; $i < $maxlevel; ++$i)
{
echo "\n</li>\n</ul>";
}
}
It arranges the array totally wrong. Have you noticed any wrong piece of code in following function?
The wrong piece is the whole logic of the function. You treat the array as a flat list (as it is!), however, you'd like to display a tree.
As a flat list can't be displayed as a tree, you need to change the flat list to a tree first and then write a function that displays a tree.
An example how to convert a flat array to a tree/multidimensional one is available in a previous answer.
Try something like this (where $array is formatted like your example):
$corrected_array = array();
// This loop groups all of your entries by their parent
foreach( $array as $row)
{
$corrected_array[ $row['parent'] ][] = $row['name'];
}
// This loop outputs the children of each parent
foreach( $corrected_array as $parent => $children)
{
echo '<ul>';
foreach( $children as $child)
{
echo '<li>' . $child . '</li>';
}
echo '</ul>';
}
Demo