PHP Object within Array within Array - php

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.

Related

PHP Curl array show only one object

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

Print a specific value from array in ci

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

Selecting value from array results

Being new to learning PHP I am having trouble with understanding how to select/echo/extract a value from array result a API script returns.
Using the standard:
echo "<pre>";
print_r($ups_rates->rates);
echo "</pre>";
The results returned look like this:
Array
(
[0] => Array
(
[code] => 03
[cost] => 19.58
[desc] => UPS Ground
)
[1] => Array
(
[code] => 12
[cost] => 41.69
[desc] => UPS 3 Day Select
)
[2] => Array
(
[code] => 02
[cost] => 59.90
[desc] => UPS 2nd Day Air
)
)
If I am only needing to work with the values of the first array result: Code 3, 19.58, UPS Ground --- what is the correct way to echo one or more of those values?
I thought:
$test = $ups_rates[0][cost];
echo $test;
This is obviously wrong and my lack of understanding the array results isn't improving, can someone please show me how I would echo an individual value of the returned array and/or assign it to a variable to echo the normal way?
echo $ups_rates->rates[0]["cost"];
See Arrays
More:
To iterate over the array
foreach ($ups_rates->rates as $rate) {
echo $rate["cost"];
// ...
}
$array = $ups_rates->rates;
$cost = $array[0]['cost'];
echo $ups_rates->rates[0]['code'];
echo $ups_rates->rates[0]['cost'];
echo $ups_rates->rates[0]['desc'];
should print out all 3
rates[0] is the first element of your array and you can index into that array by appending a ['key'] index onto the end
the only thing you forgot is ' marks

Properly extracting an embedded array from another array

I am trying to extract an array embedded in another array using the standard foreach loop, the problem is it keep returning unwanted data.
Array
Array
(
[id] => 2035443879
[status] => Unshipped
[sku] => 0340024275-UsedGood
[isbn] => 0340024275
[condition] => Used
[number_of_items] => 1
[title] => Linnets and Valerians (Knight Books)
[purchase_date] => 1361536149
[0] => Array
(
[status] => Shipped
[title] => Linnets and Valerians (Knight Books)
[date] => 1361491200
)
)
Print function
function mapStatus($orders){
foreach($orders as $order){
echo "<pre>";
print_r($order);
echo "</pre>";
foreach(array_unique($order) as $item){
echo "-".$item["status"]."-";
}
}
}
Outcome
-2--U--0--0--U--1--W--L--H--1--Shipped-
As you can see from my outcome what was printed is not exactly what I expected, it seems that I am printing the first character of every index in the array and not just the actual array I want.
I'm aware that I can use a is_array() function to determine if what I am printing is coming from an array object but I would like to know if there is proper way to do what I want?
for ($i = 0; $i < $order['number_of_items']; $i++) {
echo "-".$order[$i]["status"]."-";
}
However, I recommend a different data structure. Instead of having the items as indexed elements within the order array, you should have $order['items'], which points to an array. Then you can use:
foreach ($order['items'] as $item)
Then you don't need $order['number_of_items'], you can just use count($order['items']).

Pulling out array elements

So I am print_r-ing an array, generated as follows:
while ($twitgroup = mysql_fetch_array($resulttwitter)) {
print_r($twitgroup);
}
I get this output (with multiple more arrays, dependent on rows).
Array ( [0] => composed [category] => composed [1] => 330 [value] => 330 [2] => 1344384476.94 [timestamp] => 1344384476.94 ) Array ( [0] => elated [category] => elated [1] => 2034 [value] => 2034 [2] => 1344384476.94 [timestamp] => 1344384476.94 ) Array ( [0] => unsure [category] => unsure [1] => 2868 [value] => 2868 [2] => 1344384476.94 [timestamp] => 1344384476.94 ) Array ( [0] => clearheaded [category] => clearheaded [1] => 1008 [value] => 1008 [2] => 1344384476.94 [timestamp] => 1344384476.94 ) Array ( [0] => tired [category] => tired [1] => 2022 [value] => 2022 [2] => 1344384476.94 [timestamp] => 1344384476.94 )
I want to be able to pull individual values here, but I'm having trouble. I'm trying to use a while loop on these arrays, but I think maybe that's wrong. Should I perhaps use a foreach loop, and then on the output of that foreach, access each element of the array?
Say for example, I want to grab composed, and the value of composed. How would I do that?
I'm pretty good with arrays/lists in Python, but my experience with arrays in PHP is somewhat lacking.
Use
while ($row = mysql_fetch_assoc($resulttwitter)) {
$twitgroup[$row['category']] = $row;
}
echo $twitgroup['composed']['value']; // outputs 330
echo $twitgroup['composed']['timestamp']; // outputs 1344384476.94
If you only want categories and their values use
while ($row = mysql_fetch_assoc($resulttwitter)) {
$twitgroup[$row['category']] = $row['value'];
}
echo $twitgroup['composed']; // outputs 330
Replace mysql_fetch_array with mysql_fetch_assoc to eliminate duplicates. Then this:
while ($twitgroup = mysql_fetch_assoc($resulttwitter))
{
foreach ($twitgroup as $key => $value)
{
echo "$key => $value\n";
}
}
You could also get the elements by name:
while ($twitgroup = mysql_fetch_assoc($resulttwitter))
{
echo "category => " . $twitgroup["category"] . "\n";
echo "value => " . $twitgroup["value"] . "\n";
echo "timestamp => " . $twitgroup["timestamp"] . "\n";
}
mysql_fetch_array includes each field twice in the result, one associated with a numeric key and one with the field name.
That is why you have
[0] => composed
[category] => composed
[1] => 330
[value] => 330
You can access field either like :
$twitgroup[0]
or like :
$twitgroup['category']
So, you can access your each row like :
while ($twitgroup = mysql_fetch_array($resulttwitter)) {
print $twitgroup['category']; // or print $twitgroup['0'];
print $twitgroup['value']; // // or print $twitgroup['1'];
// or by the corresponding numeric indices.
}
If at all you want to limit your result to either numeric or Associative array, add an additional flag (result_type) to your mysql_fetch_array :
mysql_fetch_array ($resulttwitter, MYSQL_ASSOC) // or mysql_fetch_array ($resulttwitter, MYSQL_NUM)
Having said all this, it is highly discouraged using mysql_* functions in PHP since they are deprecated. You should use either mysqli or PDO instead.
This is what you have:
Array (
[0] => composed
[category] => composed
[1] => 330
[value] => 330
[2] => 1344384476.94
[timestamp] => 1344384476.94
) Array (
[] =>
[] =>
...
) ...
Arrays in PHP are called associative arrays because they can have
either keys out of integers, strings or anything else.
You have an array with arrays in it.
To access the individual fields, it would be most convenient to use a
for each loop.
$record=0;
foreach ($array as $k => $subArray) {
$record++;
foreach($subArray as $field => $value) {
printf("%d: %s = %s\n", $record, $field, $value);
}
}
Its seems to me that there is something wrong with the way you are fetching
the data, becasue half the fields seem redundant. You can use the string keys
to figure out the contents. so there is no need for the n => name entries.
If that can't be helped, I guess you could iterate over the values with
$ix=0;
for ($i=0; $i < (count($array)/2); $i++){
printf("%s\n", $array[$ix]);
$ix++;
}

Categories