foreach is playing up - php

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']

Related

limit JSON results using php

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...

echo a multidimensional array into multiple html table rows

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'));
}

Iterate through multidimensional PHP array and output values

I'm having a real headache trying to iterate through an array and output elements. Using the array structure below I want to be able to output each instance of partname.
The following loop outputs the first instance of partname. I can't seem to adapt it to loop through all instances within the array. I'm sure I'm missing something basic.
foreach($ItemsArray['assignments'] as $item) {
$partname = $item['grades'][0]['partname'];
}
Array
(
[assignments] => Array
(
[0] => Array
(
[assigntmentid] => 5101
[grades] => Array
(
[0] => Array
(
[id] => 5101
[name] => Advanced AutoCad
[partid] => 6601
[partname] => Draft
[userid] => 82069
[grade] => 53
[courseid] => 6265
[fullname] => Computer Aided Design
)
)
)
[1] => Array
(
[assigntmentid] => 5101
[grades] => Array
(
[0] => Array
(
[id] => 5101
[name] => Advanced AutoCad
[partid] => 6602
[partname] => Final
[userid] => 82069
[grade] => 35
[courseid] => 6265
[fullname] => Computer Aided Design
)
)
)
)
)
Instead of just coding by slapping the keyboard. Write down what your function needs to do. In english (or whatever language you prefer). This would be something like:
Foreach assignment, loop over all grades and store the partname of
that grade into an array.
And then code it:
function getPartnames($assignments) {
$partNames = array();
foreach ($assignments as $assignment) {
foreach($assignment['grades'] as $grade) {
$partNames[] = $grade['partname'];
}
}
return $partNames;
}
So what did I do? I simply translated english to code.
Some few more tips: Use variables names that make sense. $item; $ItemArray; ... don't make sense. They tell me nothing
use an extra foreach in your loop:
foreach($ItemsArray['assignments'] as $item) {
foreach($item['grades'] as $grade) {
echo $grade['partname'];
}
}

Foreach inside for loop complication

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

Cannot print data into "view"

I have a page that I would like to show the data from the database.
I can print_r($sale) and it shows the data that I am after - $sale is set in the controller but I cannot seem to do <?php $sale['name'] ?> it shows nothing.
Print_r:
Array ( [0] => stdClass Object ( [id] => 48 [name] => Jess McKenzie [location] => Auckland [bedrooms] => 5 [bathrooms] => 1 [condition] => Fair [description] =>
hii
[price] => 30.00000 [imagename] => purple.jpg [thumbname] => purple_thumb.jpg ) [1] => stdClass Object ( [id] => 49 [name] => jzmwebdevelopment [location] => Auckland [bedrooms] => 15 [bathrooms] => 4 [condition] => OK [description] =>
zebra
[price] => 25.00000 [imagename] => Zebra.jpg [thumbname] => Zebra_thumb.jpg ) )
Model:
function getSalesContent($id = NULL) {
$this->db->where('id', $id);
$query = $this->db->get('sales', 1);
if($query->num_rows() > 0) {
$row = $query->result_array();
return $row;
}else{
return FALSE;
} # End IF
} # End getSalesContent
It's returning an array of objects.
To show the first element returned you would use
$sale[0]->name;
To cycle through all of the values you could use a foreach loop
foreach($sale as $s){
print $s->name;
}
$query->result_array() returns an array of arrays, you would use $sale['name'] in a foreach loop.
$query->result() returns an array of stdclass objects, you would use $sale->name in a foreach loop.
I cannot seem to do $sale->name it
shows nothing.
Open your index.php file and add error_reporting(E_ALL) to the top. If you were error reporting you'd be able to see your mistakes with helpful error messages telling you exactly what went wrong. Just set it to 0 for when you go live.
I have tried <?php $sale['name'] ?> and get nothing
You need an echo statement: <?php echo $sale['name'] ?>
If $sale is the output you posted, <?php echo $sale[0]->name ?> should print Jess McKenzie

Categories