limit JSON results using php - 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...

Related

How do I loop through a multidimensional array with foreach without knowing how many items there are?

I have an array that is like this:
Array
(
[count] => 2
[results] => Array
(
[0] => Array
(
[title] => My Title 1
[description] => My amazing description
[Images] => Array
(
[0] => Array
(
[pic_url] => https://my.pic.url/01/pic01-001.jpg
)
)
)
[1] => Array
(
[title] => My Title 2
[description] => Yet another amazing description
[Images] => Array
(
[0] => Array
(
[pic_url] => https://my.pic.url/02/pic02-001.jpg
)
[1] => Array
(
[pic_url] => https://my.pic.url/02/pic02-002.jpg
)
)
)
)
)
There may be 1 item or 100 products in an array, each of which may have between 1-5 [Images]. How can I loop through each of them so that in the end I have something like:
Title:
My Title 2
Description:
Yet another amazing description
Images:
https://my.pic.url/02/pic02-001.jpg
https://my.pic.url/02/pic02-002.jpg
I was able to get the title for example with $decoded['results']['0']['title'] but I can't figure out how to display each of the titles and for each of them the unknown (1 to 5) number of image urls.
You can easily use foreach here. Also, make sure you start by iterating through your result key like $arr['result']. if this code will be placed in the front-end, you can do something like this:
$arr = array( /* your array content */ );
foreach ($arr['results'] as $result) {
?>
<div>
<div>Title:<?= $result['title'] ?></div>
<div>Description:<?= $result['description'] ?></div>
<div>
Images:
<?php foreach ($result['Images'] as $image) { ?>
<div><?= $image['pic_url'] ?></div>
<?php } ?>
</div>
</div>
<?php
}
If I understand your questions it's pretty easy. Loop through each of the results then within the foreach have another foreach which loops through the images. For example
foreach($product as $prod)
{
//logic goes here
foreach($prod['images'] as $img)
{
//do stuff with image
}
}

How to set new index in previous array using for each loop

here is my code
array 1:
Array
(
[0] => Array
(
[id] => 42166
[Company_Website] => http://www.amphenol-highspeed.com/
[company_name] => Amphenol High Speed Interconnect
[city_name] => New York
[country_name] => USA
[comp_img] =>
)
)
array 2:
Array
(
[0] => Array
(
[Product_Name] => CX to CX,Amphenol High Speed Active,Serial Attached SCSI
[company_id] => 42166
)
)
php code:
$total = count($result);
$i=0;
foreach ($result as $key=>$value) {
$i++;
$company_id= implode(",",(array)$value['id']);
if ($i != $total)
echo',';
}
code to fetch array 2:
foreach ($res as $key1=>$value1) {
echo $total;
$event[$value['company_name']] = $value1['Product_Name'];
if($value1['company_id']==$company_id )
{
echo " match";
//$key[['company_name']]= $value1['Product_Name'];
}
else
{
echo "not matched";
}
}
what i need create a new index if company_id is match with id of another array.
that is product_name.
if product name is there just create index otherwise show null.
i want show in key=> value .
output should be like:
Array
(
[0] => Array
(
[id] => 42166
[Company_Website] => http://www.amphenol-highspeed.com/
[company_name] => Amphenol High Speed Interconnect
[city_name] => New York
[country_name] => USA
[comp_img] =>
[Product_Name] => CX to CX,Amphenol High Speed Active,Serial Attached SCSI
)
)
Your all problems with keys in arrays will disappear when you will start using company ids as a keys.
To reindex you arrays, you can use:
$array1 = array_combine(array_column($array1, 'id'), $array1);
$array2 = array_combine(array_column($array2, 'company_id'), $array2);
In the output you will get:
array 1:
Array
(
[42166] => Array
(
[id] => 42166
...
)
)
And array 2 will looks similiar - id as a key.
So accessing to the elements using ids as a keys is a piece of cake right now.

JSON to PHP array issue

I have tried to use PHP decode to parse my JSON string below into an array so I can extract the current and day for both channels from the file.
my json file owl_output.json looks like..
{"channels":{"0":[{"current":1288,"units":"w"},{"day":31278.57,"units":"wh"}],"1": [{"current":660,"units":"w"},{"day":9191.11,"units":"wh"}]}}
I'am only ever getting one result displayed, the php code I have managed to get working is below
<?php
$string = file_get_contents('owl_output.json');
$data = json_decode($string,true);
print_r($json);
foreach ($data['channels']['0'] as $data)
{
echo $data ['current'];
}
?>
This only display the current for channel 0. If I try to add additional fields it doesn't display
echo $data ['current']['day']; ( doesn't work )
Can someone advise how I can display current and day for both channels 0 & 1 ?
My aim is to display this in a html page at the end and to keep polling the json file?
The array it displays is below
Array
(
[channels] => Array
(
[0] => Array
(
[0] => Array
(
[current] => 1288
[units] => w
)
[1] => Array
(
[day] => 31278.57
[units] => wh
)
)
[1] => Array
(
[0] => Array
(
[current] => 660
[units] => w
)
[1] => Array
(
[day] => 9191.11
[units] => wh
)
)
)
)
Can anyone offer any assistance with this ?
Thanks
The variable $data is conflicting:
Used to store the data, and used in the foreach loop. Rename the $data variable in the foreach for example:
<?php
$string = file_get_contents('owl_output.json');
$data = json_decode($string,true);
print_r($json);
foreach ($data['channels'] as $channel)
{
echo $channel[0]['current'];
echo $channel[1]['day'];
}
?>
I did edit since there was an other error because there is not 'current' in every record.
Conflict on $data reference in loop and bad array indexes :
foreach ($data['channels'] as $channel)
{
echo $channel[0]['current'];
echo $channel[1]['day'];
}
foreach ($data['channels'] as $chanel)
{
echo $chanel[0]['current'];
echo $chanel[1]['day'];
}

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

foreach is playing up

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

Categories