Pulling my hair out here..
My JSON output is like this:
Array (
[total] => 1
[rows] => Array (
[0] => Array (
[id] => 45
[name] => MacBook Pro (Retina 15-inch Late 2013)
[asset_tag] => 3041974
[serial] => C02M73123455
...etc...
How do I output only the [asset_tag] ?
I am using :
$responseArray=json_decode($results,true);
I have tried:
echo $responseArray['asset_tag'];
echo $responseArray[0]['asset_tag'];
echo $responseArray->asset_tag;
Thanks
You can apply foreach()
foreach($responseArray['rows'] as $row){
echo $row['asset_tag'].PHP_EOL;
}
Sample output:- https://3v4l.org/8SmuY
To access the asset_tag of all elements:
foreach ($responseArray['rows'] as $key => $value) {
echo $value['asset_tag'];
}
You can get asset_tag collection like this:
$assertTags = array_cloumn($responseArray['row'], 'asset_tag');
Related
I have an object, within an array, that is itself within an array - like this:
Array (
[0] => Array
(
[year] => 2010
[0] => stdClass Object
(
[ticker] => AAA
[exchange] => LSE
[cur_value] => 100
)
[1] => stdClass Object
(
[ticker] => BBB
[exchange] => LSE
[cur_value] => 200
)
)
[1] => Array
(
[year] => 2015
[0] => stdClass Object
(
[ticker] => AAA
[exchange] => LSE
[cur_value] => 100
)
[1] => stdClass Object
(
[ticker] => BBB
[exchange] => LSE
[cur_value] => 200
)
)
)
I want to be able to loop through the first level array, and then create a table with the data it contains. The table will use the 'year' as its name, and the the stdClass Objects will be the data that goes into the table.
The problem I am having is that that the ['year'] interferes with the first row of the table and I cannot seem to skip it - e.g. by putting a counter in and skipping the first foreach iteration or by using is_object.
The error I am getting (and I understand why I get it) is 'You are trying to get property of non-object'.
I have looked at other SO questions but they I haven't been able to find this exact problem e.g this one - Notice: Trying to get property of non-object error
Can anyone help me skip that 'year'? The PHP code I have is like this:
foreach($portfolios as $portfolio){
echo $portfolio['year'];
echo '<table>';
echo '<tr>';
echo '<th>Ticker</th>';
echo '<th>Exchange</th>';
echo '<th>Value</th>';
echo '</tr>';
foreach($portfolio as $folio){
echo '<tr>';
echo '<td>'.$folio->ticker.'</td>';
echo '<td>'.$folio->exchange.'</td>';
echo '<td>'.$folio->cur_value.'</td>';
echo '</tr>';
}
echo '</table>';
}
You could use array_splice() to remove the first element of the array so something like this:
$splicedArray = array_splice($portfolio, 0, 1);
foreach(splicedArray as $folio) {
echo '<tr>';
echo '<td>'.$folio->ticker.'</td>';
echo '<td>'.$folio->exchange.'</td>';
echo '<td>'.$folio->cur_value.'</td>';
echo '</tr>';
}
You could take a look at array_shift() or you use the key and skip that iteration in your loop. There are a lot of possibilities to solve that problem.
Or very simple use unset.
I stored some data to an array using this code ($rval['arr']):
$id = $this->input->get("id");
$rval['arr'] = $this->General_model->details($id);
When I print my result by using print_r($rval['arr']); it shows like this:
Array ( [0] => Array ( [id] => 54 [name] => Rajib [address] => DumDum [mobile] => 9865321245 [doj] => 21-2-2010 [fare] => 1245 [img_name] => Penguins.jpg ) )
Now I want to store the address value to a variable like add. How can I do this?
Try this....
$address=$rval['arr'][0]['address'];
demo
You can also do it in a foreach() loop:
foreach($rval['arr'] as $array){
echo $array['name'];
echo $array['address'];
echo $array['mobile'];
}
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 an extern JSON File and no problems to get Airline, Price, etc..
But how can i get [ACE] ?
[success] => 1
[data] => Array
(
[ACE] => Array
(
[0] => Array
(
[price] => 477
[airline] => AB
[flight_number] => 2434
[departure_at] => 2014-08-09T12:30:00Z
[return_at] => 2014-08-24T08:35:00Z
[expires_at] => 2014-04-03T22:46:17Z
)
)
$foo = $json['data']['ACE']; should do it.
Unless you want to get the key from the $data array, in which case:
foreach ($json['data'] as $k=>$v) {
$foo = $k; // this is 'ACE'.
break;
}
Edited as per comment.
['ACE'] is an array?
Your getting the data from it starting with the first - [0]
Then the ['price'] of the first one?
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'];
}