Count groups in loop foreach - php

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>";
}

Related

PHP Serialized Data output inside foreach loop

I've been stuck on this for like 2 days, and I know it's much more simpler than I think it is..
I have a foreach loop that goes like this.
foreach($appointments as $appointment){
$list = $appointment['techs']
}
The $appointment['techs']; comes out of the database like this.
a:2:{i:0;s:1:"1";i:1;s:2:"12";}
My question is, how to I get loop through appointments and then show the users that are assigned to each appointment...
The desired output should look like this,
{ resource : 1, event : 1},{ resource : 12, event : 1}
I've literally tried everything! Any help would be greatly appreciated.
$array = [];
$string = 'a:2:{i:0;s:1:"1";i:1;s:2:"12";}';
$arr = (unserialize($string));
foreach ($arr as $item){
array_push($array, json_encode(['resource'=> $item, 'event'=>1]));
}
$i = 0;
$numItems = count($array);
foreach ($array as $item) {
if (++$i === $numItems) {
echo $item;
}
else{
echo $item.',';
}
}
// Output: {"resource":"1","event":1},{"resource":"12","event":1}
The PHP command unserialize it's what you are looking for.
foreach($appointments as $appointment){
$list = unserialize($appointment['techs']);
}

PHP foreach loops and data retrieval

Using PHP and MySQL I have generated two arrays. I would like to loop through these arrays, retrieve data from both and display together in one sentence.
foreach ($items as $item) {
if(isset($item->item_title)) {
$itemTitle = $item->item_title;
}
// var_dump($itemTitle);
// string(7) "Halfway" string(5) "Story" string(6) "Listen"
}
foreach ($aData["Items"]["Item"] as $a) {
if (isset($a['description'])) {
$aDescription = $a['description'];
}
// var_dump($aDescription );
// string(4) "Good" string(6) "Strong" string(2) "OK"
}
?>
Desired result;
The title is Halfway and the description is Good.
The title is Story and the description is Strong.
The title is Listen and the description is OK.
// etc
// etc
Is it possible to nest the foreach loops, or is there a better more efficient way?
Please try this way. Hope this help!!
foreach ($items as $index => $item) {
if(isset($item->item_title)) {
$itemTitle = $item->item_title;
echo 'The title is '.$itemTitle;
}
if(isset($aData["Items"]["Item"][$index]['description']) {
$itemDescription = $aData["Items"]["Item"][$index]['description'];
echo ' and the description is '.$itemDescription;
}
echo '<br>';
// The title is Halfway and the description is Good.
}
You can merge those two foreach loops using a simple for loop, like this:
$count = count($items) >= count($aData["Items"]["Item"]) ? count($aData["Items"]["Item"]) : count($items);
for($i = 0; $i < $count; ++$i){
if(isset($item[$i]->item_title)) {
$itemTitle = $item[$i]->item_title;
}
if (isset($aData["Items"]["Item"][$i]['description'])) {
$aDescription = $aData["Items"]["Item"][$i]['description'];
}
// your code
}
Sidenote: The above code assumes that two arrays $items and $aData["Items"]["Item"] have unequal number of elements, though this will work for equal number of elements as well. If you're sure that these two arrays will always have equal number of elements, then refactor the $count = ... ; statement in the following way,
$count = count($items);
or
$count = count($aData["Items"]["Item"]);
and use this $count variable in for loop.
Try this hope this will help you out.
Note: Here i am assuming both array's have same indexes.
$items
$aData["Items"]["Item"].
If not you can do array_values($items) and array_values($aData["Items"]["Item"])
foreach ($items as $key => $item)
{
if (isset($item->item_title) && isset($aData["Items"]["Item"][$key]['description']))
{
$itemTitle = $item->item_title;
echo sprinf("The title is %s and the description is %s",$itemTitle,$aData["Items"]["Item"][$key]['description']);
echo PHP_EOL;
}
}

PHP - replace values in sub array

I have two arrays $pq and $rs. please see them below:
$pq = array ('page-0'=>array ('line-0'=>array('item-0'=>array('name'=>"item-00",'value'=>"123"),
'item-1'=>array('name'=>"item-01",'value'=>"456")
),
'line-1'=>array('item-0'=>array('name'=>"item-10",'value'=>"789"),
'item-1'=>array('name'=>"item-11",'value'=>"012")
)),
'page-1'=>array ('line-0'=>array('item-0'=>array('name'=>"item-100",'value'=>"345"),
'item-1'=>array('name'=>"item-101",'value'=>"678")
),
'line-1'=>array('item-0'=>array('name'=>"item-110",'value'=>"901"),
'item-1'=>array('name'=>"item-111",'value'=>"234")
),
'line-2'=>array('item-0'=>array('name'=>"item-210",'value'=>"567"),
'item-1'=>array('name'=>"item-211",'value'=>"890")
))
);
$rs = array ('1'=>array('name'=>'item-00', 'value'=>"abc"),
'2'=>array('name'=>'item-01', 'value'=>"def"),
'3'=>array('name'=>'item-10', 'value'=>"ghi"),
'4'=>array('name'=>'item-11', 'value'=>"jkl"),
'5'=>array('name'=>'item-100', 'value'=>"mno"),
'6'=>array('name'=>'item-101', 'value'=>"pqr"),
'7'=>array('name'=>'item-110', 'value'=>"stu"),
'8'=>array('name'=>'item-111', 'value'=>"vwx")
);
What I am trying to do is to replace the values in $pq for items with the values from $rs.
for example item-01 in $pa to be replaced with abc from $rs.
What I tried is this:
foreach($rs as &$rs1) {
echo "first count :".$firstCount."<br>";
foreach($pq as $pages) {
foreach($pages as $lines) {
foreach($lines as &$item) {
if ($item['name'] == $rs1['name']) { echo "matching </p>";
$item['value']=$rs1['value'];
echo '<pre>';
print_r($item);
echo '</pre>';
echo "<hr>";
}
}
}
}
}
When I print the values of $item from $pq, it prints the values from $rs, but when I print the whole array $pq, the values seem to be unchanged.
Can anyone please help me find out what I am missing ?
You're correctly looping through the items in each line by reference, but you're not doing it for the lines or pages themselves. So you're updating the value of an item in a copy of the line, instead of the line itself. It should be:
foreach($rs as $rs1) {
echo "first count :".$firstCount."<br>";
foreach($pq as &$pages) {
foreach($pages as &$lines) {
foreach($lines as &$item) {
if ($item['name'] == $rs1['name']) { echo "matching </p>";
$item['value']=$rs1['value'];
echo '<pre>';
print_r($item);
echo '</pre>';
echo "<hr>";
}
}
}
}
}
Note that the & in front of &$lines and &$pages. Note also that $rs1 doesn't need to be passed by reference, since you aren't changing anything in that array.
You’ve assigned $item by reference but haven’t done the same for $pages and $lines. There will be no effect on the actual values of $pq unless you assign $pages by reference; similarly, the actual values of $pages will remain unchanged unless you assign $lines by reference. Therefore, in order to achieve what you want, change foreach($pq as $pages) to foreach($pq as &$pages) and foreach($pages as $lines) to foreach($pages as &$lines).
You can build a search array first so that you can match items easier:
$search = array_reduce($rs, function(&$prev, $current) {
$prev[$current['name']] = $current;
return $prev;
}, []);
This creates another array with the item name as the key. Then, you iterate over each item in $pq and modify the leaves where necessary:
foreach ($pq as &$page_data) {
foreach ($page_data as &$line_data) {
foreach ($line_data as &$item_data) {
if (isset($search[$item_data['name']])) {
$item_data = $search[$item_data['name']];
}
}
}
}
Make sure to use references at each level of iteration.

for loop append variable php

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>";

loop through an array and show results

i m trying to do a loop but get stacked ,
i have a function that convert facebook id to facebook name , by the facebook api. name is getName().
on the other hand i have an arra with ids . name is $receivers.
the count of the total receivers $totalreceivers .
i want to show names of receivers according to the ids stored in the array.
i tried every thing but couldnt get it. any help will be appreciated . thanks in advance.
here is my code :
for ($i = 0; $i < $totalreceivers; $i++) {
foreach ( $receivers as $value)
{
echo getName($receivers[$i]) ;
}
}
the function :
function getName($me)
{
$facebookUrl = "https://graph.facebook.com/".$me;
$str = file_get_contents($facebookUrl);
$result = json_decode($str);
return $result->name;
}
The inner foreach loop seems to be entirely redundant. Try something like:
$names = array();
for ($i = 0; $i < $totalReceivers; $i++) {
$names[] = getName($receivers[$i]);
}
Doing a print_r($names) afterwards should show you the results of the loop, assuming your getNames function is working properly.
Depending of the content of the $receivers array try either
foreach ($receivers as $value){
echo getName($value) ;
}
or
foreach ($receivers as $key => $value){
echo getName($key) ;
}

Categories