I'm having trouble with a loop inside another one. I don't know how to handle this situation and I don't get the expected result - I get my expected result but multiplied.
This is my code:
<div id="view">
<?php
for ($i = 0; $i < sizeof($user_roll_array); $i++):
$roll_data =& $user_roll_array[$i];
$roll_date = $roll_data['time'];
$roll_ids = $roll_data['image_ids'];
$roll_ids = explode('|', $roll_ids);
$roll_key = $roll_data['key'];
foreach ($roll_ids as $image_id):
$image_name = $image->get_name($image_id);
?>
<div class="roll-spot">
<?php echo $image_name; ?>
</div>
<?php endforeach; endfor; ?>
</div>
This is what $user_roll_array contains:
Array
(
[0] => Array
(
[id] => 1
[user_id] => 1
[image_ids] => 10|9
[time] => 1359244752
[key] => 8O0F5k8G9Y1H4b7
)
[1] => Array
(
[id] => 2
[user_id] => 1
[image_ids] => 13|12|11|10|9
[time] => 1359245133
[key] => n9G7v49E2Q5h0j7
)
[2] => Array
(
[id] => 3
[user_id] => 1
[image_ids] => 13|12
[time] => 1359285360
[key] => 2Q0t1Z3S2r7n5f9
)
[3] => Array
(
[id] => 4
[user_id] => 1
[image_ids] => 10|9
[time] => 1359285377
[key] => 4L6w6R2r2Q0c1g9
)
[4] => Array
(
[id] => 7
[user_id] => 1
[image_ids] => 10|9
[time] => 1359288800
[key] => 4t1X9P8l9H7C1F6
)
)
Based on the array I create inside the for loop, I need to go through each element and get its name via a method ($image->get_name($id)). Then I need to use these names below.
I expect 5 rows to be returned, but I get 13 rows, and the names are duplicated a few times.
If someone could explain how to fix this, I'd understand the issue and prevent future similar problems to occur.
Thanks a lot.
The reason you are getting 13 results is because although there are 5 top-level iterations, there are 13 sub-iterations (the IDs) which you are looping through.
If you want just the 5 iterations to happen, you shouldn't be doing the sub-loop within them. This is the part of your code which is confusing you:
<? foreach ($roll_ids as $image_id): ?>
<? $image_name = $image->get_name($image_id); ?>
<div class="roll-spot">
<?php echo $image_name; ?>
</div>
<?php endforeach;?>
This foreach is itself inside the main loop, and echoing out a div for each ID has access to. In the life cycle of the main array, this will happen 13 times. The reason you are seeing duplicates is because you have top-level array elements which contain the same IDs as other elements.
remove the ampersand in
$roll_data =& $user_roll_array[$i];
Related
I have here an array below:
<?php
print_r( $result );
?>
If I am going to execute the code above, it resulted below:
Array
(
[0] => Array
(
[id] => 1
[uploaded_by] => 1
[image_url] => http://localhost/dir/img_2.jpg
[work_description] => test
[date_added] => 2017-08-03 02:12:38
)
[1] => Array
(
[id] => 2
[uploaded_by] => 1
[image_url] => http://localhost/dir/img_4.jpg
[work_description] => test
[date_added] => 2017-08-03 02:13:04
)
[2] => Array
(
[id] => 3
[uploaded_by] => 1
[image_url] => http://localhost/dir/img_2.jpg
[work_description] => test
[date_added] => 2017-08-03 02:46:28
)
[3] => Array
(
[id] => 4
[uploaded_by] => 1
[image_url] => http://localhost/dir/img_2.jpg
[work_description] => sdfsdf
[date_added] => 2017-08-03 02:46:34
)
)
Now, from the $result array I wanted to change the values of all image_url
programmatically using php into an image in html.
example:
http://localhost/dir/img_2.jpg will become
<img src="http://localhost/dir/img_2.jpg"/>
Those values must be changed if I am going to execute the code.
Does anybody know?
You can put it in a foreach and modify only the part what you want:
foreach($result as $key => $value) {
$result[$key]['image_url'] = '<img src="'.$value['image_url'].'"/>';
}
print_r($result);
You can use a compact syntax and modify the subarray elements by reference:
Code: (Demo)
foreach ($result as &$subarray) { // & means modify by reference, so you are overwriting the input array, not traversing a copy.
$subarray['image_url'] = "<img src=\"{$subarray['image_url']}\"/>";
}
var_export($result);
There is no need to declare $key because the foreach is traversing the actual input array, not a copy of the input array. The image_urls are simply overwritten with each iteration.
I need to compare element from an array to another array with in_array() method:
$oldAttachedObjs = array();//this array need to be compare with single element of other loop
$sqlObjAttached = "SELECT sno,ins_sno,obj_sno FROM cases_objections WHERE ins_sno = :ins_sno";
$paramObj = array(':ins_sno'=>$ins_sno);
if($db->dbQuery($sqlObjAttached,$paramObj)){
foreach($db->getRecordSet($sqlObjAttached,$paramObj) as $o){
$oldAttachedObjs[] = $o;
}//foreach()
}
Now i want to compare the above array elements with each element in the iterated loop over the following loop
<?php
$sqlChildren = "SELECT sno,obj_sno,child_lbl FROM list_objection_children WHERE is_active = 1 AND obj_sno = :obj_sno ORDER BY sno ASC";
$param = array(':obj_sno'=>$obj['sno']);
if($db->dbQuery($sqlChildren,$param)){
foreach($db->getRecordSet($sqlChildren,$param) as $ch){
?>
<ul class="obj_ul">
<li>
<div class="checkbox checkbox-primary">
<?php print_r($oldAttachedObjs[0]); ?>
<input type="checkbox" <?php if(in_array($ch['sno'],$oldAttachedObjs['obj_sno'])){ ?> checked <?php //} ?> value="1" id="chk_<?php echo($ch['sno']);?>" name="chk_<?php echo($ch['sno']);?>" class="styled">
<label style="font-weight: normal !important;" for="chk_<?php echo($ch['sno']);?>"><?php echo($ch['child_lbl']); ?></label>
</div>
</li>
</ul>
<?php
}//foreach()
}
?>
in fact it populate the following array:
Array (
[0] => Array ( [sno] => 1 [0] => 1 [ins_sno] => 2 [1] => 2 [obj_sno] => 3 [2] => 3 ),
[1] => Array ( [sno] => 2 [0] => 2 [ins_sno] => 2 [1] => 2 [obj_sno] => 49 [2] => 49 ),
[2] => Array ( [sno] => 3 [0] => 3 [ins_sno] => 2 [1] => 2 [obj_sno] => 52 [2] => 52 ),
[3] => Array ( [sno] => 5 [0] => 5 [ins_sno] => 2 [1] => 2 [obj_sno] => 54 [2] => 54 )
)
but i have no luck to compare, because the array contained with another array and i don't know what to do with this now ?
You need to loop through the parent array to compare to the inner arrays.
foreach($oldAttachedObjs as $objs){
if(in_array('what you are looking for', $objs){
//it is in the array, do what you want
}else{
//it is not in the array, deal with it accordingly
}
}
This way you'll be able to check wether whatever you're looking for is inside one of the results you got from the database
I am facing with a problem that my json results cannot be limited..
My json result contains a large number of data, I just want to limit the results so that i can print some of the data in my view page. How can i do that?
Here is my code
$post1 = file_get_contents("........");
$products = CJSON::decode($post1, true);
for($i=1;$i<=5;$i++)
{
echo "<pre>";print_r($products);
}
This code prints all the contents. Please help me with this ,waiting for the response.
Output of $products.
Array
(
[0] => Array
(
[id] => 4380
[title] => 13 Thirteen Patch
[barcode] => PAT-2288
[qty] => 17
[url] => http://www.heygidday.biz/13-thirteen-motorcycle-club-mc-fun-embroidered-quality-new-biker-patch-pat-2288.html
[retail_price] => 4.99
[category] => Array
(
[id] => 1
[name] => SMALL PATCHES
)
[bin] => Array
(
[id] => 1
[name] => A1
)
[images] => Array
(
[0] => Array
(
[small] => http://www.heygidday.biz/portal//timthumb.php?src=/files/products/pat-2288-013678719880.jpg&w=30
[middle] => http://www.heygidday.biz/portal//timthumb.php?src=/files/products/pat-2288-013678719880.jpg&w=100
[source] => http://www.heygidday.biz/portal/files/products/pat-2288-013678719880.jpg
)
)
)
....................
[6619] => Array
(
[id] => 12921
[title] => Special Police- BLACK Leather Key Fob
[barcode] => FOB-0435
[qty] => 1
[url] =>
[retail_price] => 8.99
[category] => Array
(
[id] => 54
[name] => KEY FOBS
)
[bin] => Array
(
[id] => 382
[name] => F10-21
)
[images] => Array
(
)
)
)
Hope this is useful.
Simpler answer
Just use array_slice to take out the number of elements you want:
echo "<pre>";
print_r(array_slice($products,0,5));
echo "</pre>";
The pitfalls I pointed to in Ben's answer are still relevant.
Original answer
print_r($products) will print the entire array each time through the loop. To limit the number of elements printed to 5, do:
Replace your for loop with:
for($i=0;$i<(min(5,count($products)));$i++):
echo "<pre>";
print_r(each($products)['value']);
echo "</pre>";
endfor;
Two pitfalls to watch out for in Ben Shoval's answer:
You should add a safeguard against going beyond the end of the array. If your $products has just 3 items, and you loop 5 times, you will run into an error. That's why I have the max $i set to min(5,count($products)
If you use the index $i to refer to each element, your code will fail if $products is an associative array (with named keys instead of indices 0,1...). This is why I use each($products)['value'] to access the value when I don't know the key
Change:
echo "<pre>";print_r($products);
To:
echo "<pre>";print_r($products[$i]);
You did wrong code, you have printed json decode resposne 5 times.
You should check what keys in the json decoded response and then try to get specific data you want.
For example:
if you want first 5 elements of response then:
$c = 0;
foreach($products as $p){
print_r($p);
$c++;
if($c == 5){
break;
}
}
I got the answer.This is how i done ........
Controller
$data = file_get_contents("............",true);
$result = json_decode($data);
$prod = array();
$i =0;
foreach($result as $rest){
$product = json_decode(json_encode($rest),true);
foreach($product as $prods){
$prod[] = array_merge($prods);
}
$new_array = array_slice($prod, 0, 5);
$this->render('index',array('model'=>$model,'products'=>$new_array));
}
View page
<?php
foreach($product as $prod):
?>
<li style="width: 200px;">
<?php
$img = array();
foreach($prod['images'] as $img):
//echo $img['middle'];
echo CHtml::image($img['source'],'',array('alt'=>'Image 3'));
// $i++;
endforeach;
// echo CHtml::link($img,'detail');
?>
<div class="list-holder">
<h4><?php echo $prod['title'];?></h4>
<div class="rating"> <span>$<?php echo $prod['retail_price'];?></span></div>
</div>
</li>
<?php
endforeach;
?>
This code displayed first 5 products in my view..
Thanks for all the answers provided and time...
I have a query that I'm running and it will output an unknown number of results. I want to display these results in a table of 5 columns. So I need the array print until the sixth result and then start a new row.
The way I tried to do it was to take the original array and chunk it into blocks of 5.
$display=array_chunk($row_Classrooms,5);
which gives me an array like this.
Array (
[0] => Array (
[0] => Array (
[id_room] => 1
[Name] => Classroom 1
[class] => Yes
)
[1] => Array (
[id_room] => 5
[Name] => Classroom 2
[class] => Yes
)
[2] => Array (
[id_room] => 6
[Name] => Classroom 3
[class] => Yes
)
[3] => Array (
[id_room] => 7
[Name] => Classroom 4
[class] => Yes
)
[4] => Array (
[id_room] => 8
[Name] => Classroom 5
[class] => Yes
)
)
[1] => Array (
[0] => Array (
[id_room] => 9
[Name] => Classroom 6
[class] => Yes
)
)
)
I'm then trying to echo this out with a pair of while loops, like such.
while ($rows = $display) {
echo '<tr>';
while ($class = $rows) {
echo'<td>'.$class['name'].'<br>
<input name="check'.$i.' type="checkbox" value="'.$class['id_room'].'></td>';
$i++;
}
echo '</tr>';
}
When I run this it apparently gets stuck in a never ending loop because nothing gets displayed but the browser just keeps chewing up more and more memory :)
The while statements are wrong. Have a look at here - in your while-statement you are always assigning the complete $display - not one entry.
You could try using while(($rows = array_shift($display)) !== false) - that will always get the first array item until there are no more items.
The same case in the second while-statement.
I ended up replacing the while loops with foreach loops instead which solved the issue.
foreach ($display as $rows) {
echo '<tr class="popup">';
foreach($rows as $class) {
if(isset($row_Rego)){
$exist=NULL;
$exist=array_search($class['id_room'], array_column($row_Rego, 'id_room'));
}
I have two arrays:
$item dates basicaly looks like this:
Array (
[0] => 2012-05-28
[1] => 2012-05-29
[2] => 2012-05-30
[3] => 2012-05-31
[4] => 2012-06-01
)
and $m['details'] looks like this:
Array (
[details] => Array (
[0] => Array (
[Id] => 20003
[MTimeInt] => 0
[Date] => 2012-05-28
[Name] => item
)
[1] => Array (
[Id] => 20004
[MTimeInt] => 1
[Date] => 2012-05-29
[Name] => item2
)
[2] => Array (
[Id] => 20005
[MealTimeInt] => 0
[Date] => 2012-05-29
[Name] => item3
)
)
)
//start of main bit
<?php foreach($m['details'] as $item) { ?>
<?php if($item['MTimeInt'] == 0 && $item['Date'] == $itemDates[0]) { ?>
<?php echo $item['Name']; ?> <br>
<?php } ?>
<?php if($item['MTimeInt'] == 0 && $item['Date'] == $itemDates[1]) { ?>
<?php echo $item['Name']; ?>
<?php } ?>
<?php } ?>
The problem I am having the foreach loop breaks after it has iterated once. When after the if statement has been fulfilled it should continue looping (by moving onto the next index/item onto the list) until all of the items have been checked.
I previously used a while loop without much success.
Any idea why this is happening?
Thanks
The $m['details'] have only one element, look closer.
Maybe want you iterate over $m['details']['details'] ?
If the code you show is correct, then inside $m['details'] there is another ['details'], which would explain the single iteration.
You are calling foreach on a single array item. You should see what happens if you call it on $m singly and Seperate the items you need after with if. I will expand my answer properly when I get to a pc
You are not iterating through the right array, in your case in the array you have only one item, try with $m['details']['details']