Foreach inside foreach Strange Bug - php

<?php
foreach($products as $product){
//some code here , echoing products and everything works there
foreach($types as $type){
echo $type['type'];
// only does the echo on the first occurence of this "types" loop
}
}
?>
Hi everyone,
I'm making a type of form in order to allow people, for each product of the database, to specify the type of the product.
$products and $types are both distinct arrays. Products contains all my products and $types contains all my types.
Actually I have only 2 products and 2 types.
So, my question is: Why the echo doesn't show anything for the second occurence of the foreach($products as $product), and show the good results at the first occurence?
This is exactly the same array, called 2 times, but working only at the first occurence of the loop. Very Strange for me.
Hope you'll understand despite my poor english.
Bye

Let's assume there are 4 products and 7 types. With the following code you are executing the outer loop 4 times and the inner loop 7 times. What is printed is the content of $type['type'] for all 7 items. And this 4 times.
<?php
foreach($products as $product){
foreach($types as $type){
echo $type['type'];
}
}
?>
What you need is a $products array that contains the types for the product, so that you can use the following code
<?php
foreach($products as $product){
foreach($product->type as $type){
echo $type['type'];
}
}
?>

This happens because on the second loop, $type is still a reference to the last array item, so it's overwritten each time.
You can see it like that:
$types = array ('type-one','type-two','type-three');
foreach ($types as $type) {
echo $type;
}
foreach ($types as $type) {
echo $type;
}
As you can see, the second time you call the array. It will not echo anything.
There is no "bug" in your code. It just happens like that
To solve it. You can use this code before the second loop. It will reset the array reference.
reset($types);

Related

PHP: Append array in foreach loop with elements on condition with matching elementId

I have an array with with different code numbers, and in turn each code can refer to different items. However, every code can refer to many items, while every item can have many codes (i.e. many-to-many relation between codes and items).
I have the items and I have the item codes, and now I want to append the right codes to the right items via a loop in a code snippet looking this (each $itemCode object includes an $item.Id property):
foreach($itemCodes as $itemCode) {
$itemCodesForItem = [];
foreach($items as $item) {
if($itemCode->getItem()->getId() == $item->getId()) {
array_push($itemCodesForItem, $itemCode->getCode());
$item->setCode($itemCodesForItem); // Assign with array with all appended codes for a specific item
}
}
}
The issue here is that every matching code overwrites the previous matching one, so in the end it only assigns one code to each item. But if an item has several codes, I want all those codes appended in the array for the specific item, and not only the last matching one. Does anyone know how to catch and append the right codes to the right items here?
Ok, so finally I got it working with the following code:
foreach($items as $item) {
$itemCodesForItem = [];
foreach($itemCodes as $itemCode) {
while($itemCode->getItem()->getId() == $item->getId()) {
array_push($itemCodesForItem, $itemCode->getCode());
$item->setCode($itemCodesForItem);
break;
}
}
}

How to get each value in a column of database in php

I don't have enough knowledge about this criteria:
I want to loop inside the for each loop to get all values in a particular column.
For example: I got the values from DB through get_result and store the result in $results.
After that use:
for each($results as $result)
❴
$output = $result->message
❵
Where message is a column in DB.
I want to loop over all the messages instead of storing last one by replacing.
Can you please give me suggestions on how to loop inside for each?
Try this:
$output[] = $result ->message;
Now $output will contain all messages on index 0, 1, 2 ...
You are facing the issue because:
$output=$result ->message;
the above line is present inside the loop, and each new iteration onerride the old value.
Well if you just looking for foreach inside foreach then you can try the following.
<?php
foreach($results as $result){
$output=$result->message;
foreach($output as $messages){
echo $messages;
}
}
?>
You don't need to put the message into another variable. You can do whatever you need to do inside the loop. For example, if you are displaying the messages, you can get it done inside the loop:
foreach ($results AS $result) {
echo $results->message . "<br>";
}

Php foreach restriction before the loop

I got an array of news items parameters that I loop trough and get the results out
is there any way I loop the array for specific items before I do the foreach ,
I want to loop only trough post with specific category which is fetched before the foreach
$get_cats = $k2tools_params->get('cloud_category');
returns an array of allowed categories
than I have
<?php foreach($this->items as $key=> $item): >
<?php if (in_array($item->category->id,$get_cats)){ ?>
// do something
<?php} ?>
<?php endforeach ?>
<?php echo $this->pagination->getPagesLinks(); ?>
this works fine but the issue I have is the pagination wich counts 18 items from $this->items
and I have 3 pages of results , but in foreach with my category restriction I have only 2 items , and this is causing additional 2 empty pages.
so I must restrict the categories befre the foreach , or loop trough $this->items first
thnx for any help , I hope you understand .
dont mind the php tags separating html from php this is joomla templating
what I kinda want to do is foreach where category id is in array ,
In order to that properly with pagination, you will have to find some way to modify the original SQL query.
foreach(array_keys($items, $get_cats)) {
// do_something
}
or try to use array_search

Display most voted posts

I'm using ThumbsUp V2 Voting Script and i'm trying to display the posts based on the number of votes:
<?php $items = ThumbsUp::items()->orderby('votes_total')->get() ?>
The values are stored in mysql so i thought of:
$display = mysql_query("SELECT * FROM banat");
$items = ThumbsUp::items($display)->orderby('votes_total')->get() ;
But i thik i've definitely done this wrong since it's just displaying an output:
Array
If you get an array, you must loop on it to show the data. You cannot just do an echo on a var that is an array. You should have something like this:
foreach($items as $item)
{
echo $item;
}
Your $items is an array, and I assumed you attempted to
echo $items;
Instead you will need to loop over it:
foreach ($items as $item) {
// View the structure of `$item`
print_r($item);
}
If you only expect $items to hold one thing, then just do:
print_r($items[0]);

adding an element to multidimensional array when within foreach loop (PHP)

I'm trying to check if a certain category is allready selected by looping through an array of categories also I want to add another element to the array whci is just a bit to indicate is the category selcated
my categories array looks like this
0=>array(category_id=>12,category_name=>"blogger")
1=>array(category_id=>13,category_name=>"dancer")
etc...
now the code i'm trying goes like that:
foreach ($userCategories as $key=>$category) {
if($category['category_id'] == $mediaDetails['currentCategory']) {
$category['current'] = 1;
} else {
$category['current'] = 0;
}
}
when executing
die(var_dump($userCategories));
I expect to get an array similar to
0=>array(category_id=>12,category_name=>"blogger",current=>0)
1=>array(category_id=>13,category_name=>"dancer",current=>1)
but instead I get the same array I had before the foreach loop
any ideas?
Thanks
It looks like $category is not getting passed by reference.
Try $userCategories[$key]['current']=1 instead, and see how that works.

Categories