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;
}
}
Related
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>";
}
I have an array with products, filled by the API.
I want to extend it and add some values like categories, price. I tried to add & before the array when looping to use it by reference row. But when I added another while loop to add categories, the $row wasn't extended.
$products = array('id_product'=>12,'link'=>'test.html','description'=>'desc');
foreach($products as &$row) {
$row['price'] = 12;
$product = new Product($row['id_product'];
$categories = $product::getCategories();
$k = 1;
while ($cat = current($categories)){
$row['categoryid'.$k] = $cat['name'];
$k++;
}
}
$product::getCategories() return
array(1) { [0]=> array(1) { ["name"]=> string(8) "T-shirts" } }
The problem is that the array key with categoryid.$k is never created, I tried with foreach on categories but it didn't work.
In provided example in foreach loop $row will contains values 12, 'test.html' and 'desc'. So you can't use them as array.
Valid code:
$products = array();
$products[] = array('id_product'=>12,'link'=>'test.html','description'=>'desc');
Also you have invalid while loop, replace current function with array_shift, or use proper foreach loop
Edited:
Replace while with this code:
if (!empty($categories)) {
foreach ($categories as $key => $category) {
$row['categoryid' . $key] = $category['name'];
}
}
I fixed my problem by adding a function and pass by value the row parameter
private function addCategories(&$row){
$categories = $this->getProductCategoriesFull((int)$row['id_product']);
if (!empty($categories)) {
$k = 2;
foreach($categories as $category) {
if($k!= 2)
$row['categoryid' . ($k-1)] = $category['name'];
$k++;
if($k>5) exit;
}
}
}
And call it in the loop
$this->addCategories($row);
Need little help, i get always stupid errors, when i try to do this, i want to foreach array, and inside that do a for loop, is this possible?
Here is my code
$image = new SimpleImage();
$slike=array($_FILES['slika1']['tmp_name'],$_FILES['slika2']['tmp_name'],$_FILES['slika3']['tmp_name'],$_FILES['slika4']['tmp_name']);
$koliko = count($slike);
foreach ($slike as $slika) {
for ($i = 1; $i <= $koliko; $i++)
{
$slicica="../images/usluge/".mysql_insert_id()."-".$i.".jpg";
$image->load($slika);
$image->resizeToWidth(800);
$image->save($slicica);
}
}
I want to get new pictures with this name, example.If last id was 2 i want to get this filenames etc
2-1.jpg
2-2.jpg
2-3.jpg
2-4.jpg
Still with my code i dont get correct values :(
Or maybe there is easy way to do that :)
I think what you need is to replace your following line:
$image->load($slika);
for this one:
$image->load($slike[$i-1]);
you probably have a problem in you foreach as if we do a var_dump on an array we will see the following :
array(3) { [0]=> string(5) "test1" [1]=> string(4) "tes2" [2]=> string(5) "test3" }
so you need to change it to :
foreach ($slike as $key => $slika) {
you can also use move_uploaded_file to achieve what you are trying to do and use linux command convert :
foreach ($slike as $key => $slika) {
for ($i = 1; $i <= $koliko; $i++)
{
$slicica="../images/usluge/".mysql_insert_id()."-".$i.".jpg";
if(move_uploaded_file(slika,slicica)){
exec("convert $slicica -resize 200 $slicica");
}else{die('problem loading the file');}
}
}
$i=1;
// insert into mysql table..
// [...]
$mysqlId = mysql_insert_id();
foreach ( $_FILES as $key => $value) {
$slicica="../images/usluge/".$mysqlId."-".$i.".jpg";
if(move_uploaded_file($_FILES[$key]["tmp_name"],slicica)){
$image->load($slicica);
$image->resizeToWidth(800);
$image->save($slicica);
}
else {
// error handling
}
$i++;
}
How to calculate how many items in a foreach?
I want to count total rows.
foreach ($Contents as $item) {
$item[number];// if there are 15 $item[number] in this foreach, I want get the value : 15
}
If you just want to find out the number of elements in an array, use count. Now, to answer your question...
How to calculate how many items in a foreach?
$i = 0;
foreach ($Contents as $item) {
$item[number];// if there are 15 $item[number] in this foreach, I want get the value : 15
$i++;
}
If you only need the index inside the loop, you could use
foreach($Contents as $index=>$item) {
// $index goes from 0 up to count($Contents) - 1
// $item iterates over the elements
}
You don't need to do it in the foreach.
Just use count($Contents).
count($Contents);
or
sizeof($Contents);
foreach ($Contents as $index=>$item) {
$item[$index];// if there are 15 $item[number] in this foreach, I want get the value : 15
}
There's a few different ways you can tackle this one.
You can set a counter before the foreach() and then just iterate through which is the easiest approach.
$counter = 0;
foreach ($Contents as $item) {
$counter++;
$item[number];// if there are 15 $item[number] in this foreach, I want get the value : 15
}
Try:
$counter = 0;
foreach ($Contents as $item) {
something
your code ...
$counter++;
}
$total_count=$counter-1;
$Contents = array(
array('number'=>1),
array('number'=>2),
array('number'=>4),
array('number'=>4),
array('number'=>4),
array('number'=>5)
);
$counts = array();
foreach ($Contents as $item) {
if (!isset($counts[$item['number']])) {
$counts[$item['number']] = 0;
}
$counts[$item['number']]++;
}
echo $counts[4]; // output 3
foreach ($array as $value)
{
if(!isset($counter))
{
$counter = 0;
}
$counter++;
}
//Sorry if the code isn't shown correctly. :P
//I like this version more, because the counter variable is IN the foreach, and not above.
You can do sizeof($Contents) or count($Contents)
also this
$count = 0;
foreach($Contents as $items) {
$count++;
$items[number];
}
Imagine a counter with an initial value of 0.
For every loop, increment the counter value by 1 using $counter = 0;
The final counter value returned by the loop will be the number of iterations of your for loop. Find the code below:
$counter = 0;
foreach ($Contents as $item) {
$counter++;
$item[number];// if there are 15 $item[number] in this foreach, I want get the value `: 15`
}
Try that.
$index = 0;
foreach( $array ?? [] as $index=> $item ) {
$index++;
$data[] = array(
'id' =>$index
);
}
Using a regular for loop, it's possible to comapred the current index with the last to tell if I'm in the last iteration of the loop. Is there a similar thing when using foreach? I mean something like this.
foreach($array as $item){
//do stuff
//then check if we're in the last iteration of the loop
$last_iteration = islast(); //boolean true/false
}
If not, is there at least a way to know the current index of the current iteration like $iteration = 5, so I can manually compare it to the length of the $array?
The counter method is probably the easiest.
$i = count($array);
foreach($array as $item){
//do stuff
//then check if we're in the last iteration of the loop
$last_iteration = !(--$i); //boolean true/false
}
You can use a combination of SPL’s ArrayIterator and CachingIterator class to have a hasNext method:
$iter = new CachingIterator(new ArrayIterator($arr));
foreach ($iter as $value) {
$last_iteration = !$iter->hasNext();
}
Here are a few methods for this;
$items = ["Bhir", "Ekky", null, "Uych", "foo"=>"bar"];
$values = array_values($items);
// Bhir, Ekky, Uych, bar
foreach ($values as $i => $item) {
print("$item");
$next = isset($values[$i + 1]);
if ($next) {
print(", ");
}
}
// Bhir, Ekky, , Uych, bar
foreach ($values as $i => $item) {
print("$item");
$next = array_key_exists($i + 1, $values);
if ($next) {
print(", ");
}
}
// Bhir, Ekky, , Uych, bar
$i = count($values);
foreach ($items as $item) {
print("$item");
$next = !!(--$i);
if ($next) {
print(", ");
}
}
// Bhir, Ekky, , Uych, bar
$items = new \CachingIterator(new \ArrayIterator($items));
foreach ($items as $item) {
print("$item");
$next = $items->hasNext();
if ($next) {
print(", ");
}
}
No, you need to have a counter and know the amount of items in the list. You can use end() to get the last item in an array and see if it matches the current value in your foreach.
If you know that the values of the array will always be unique, you can compare the current $item to end($array) to know if you're at the last item yet. Otherwise, no, you need a counter.
You can get the key and the value in foreach() like this:
foreach($array as $key=>$value) { ... }
Alternatively, you could do a count() of the array so you know how many items there are and have an incrementing counter so that you know when you've reached the last item.
end($array);
$lastKey = key($array);
foreach($array as $key => $value) {
if ($key === $lastKey) {
// do something endish
}
}
The valid() method says if the ArrayIterator object has more elements.
See:
$arr = array("Banana","Abacaxi","Abacate","Morango");
$iter = new ArrayIterator($arr);
while($iter->valid()){
echo $iter->key()." - ".$iter->current()."<br/>";
$iter->next();
}