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
Related
I have some data, one array from CSV File, another array contains a value of a field in a post.
With this data, i would like to check if the value of the field is in the CSV then update the field, if not and there is a difference to insert the field into a post.
$csv_data array has lots more fields than $vrm array. I think I need a function that says, if element is in array then, however I am unsure how to do this.
Here is what I have so far:
$vrm = [];
foreach($vehicles as $vehicle) {
$vrm[] = $vehicle->REGISTRATION;
}
$difference = array_diff($csv_data, $vrm);
if(empty($difference)) {
echo "Need to Update";
} else {
echo "Need to insert";
}
Is anyone able to assist me with this or point me in the right direction please?
** EDIT **
Array $vrm is:
Array ( [0] => CV56IPG,
[1] => RT56KLP,
[2] => AB12HNJ)
Array $csv_data is:
Array ( [0] => Array (
[REGISTRATION] => CV56IPG
[MAKE] => Volkswagen
[MODEL] => Polo
[DERIVATIVE] => 1.2 Match 5dr
)
[1] => Array (
[REGISTRATION] => AB12HNJ
[MAKE] => Volkswagen
[MODEL] => Polo
[DERIVATIVE] => 1.2 Match 5dr
)
)
I don't exactly understand your word.
I guess, If you have $vrm unique id, If you use haspMap, you can do this.
{
vrm_id1: vrm_data1,
vrm_id2: vrm_data2
}
if you insert or update new data.
when vrm_id is not exist => insert.
when vrm_id is exist => update.
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 have an array that is put together. It's basically 24 data points across 7 stations. Each station has a data point each hour and a new sub0array is created for each data point. The problem with this, is I now want to split the data up based on station so I can sort it. When I go to do that array_filter doesn't work for me. I wanted to basically combine all of the values that have the same row 0 result in each sub-array. but keep each data point based on them. Row 0 is the station name. Here is an example of what the array looks like. There are 160 sub arrays. All I need to do is combine them together based on Station name. I was going to do this based on Array value, but the problem is if a data-point is missing, it breaks that logic.
Array
(
[0] => Array
(
[0] => STATIONONE
[1] => 02/22/15 04:00:00 PM
[2] => SW
[3] => Array
(
[0] => 4.51
)
[4] => MPH
[5] => Array
(
[0] => 16.1
)
[6] => MPH
)
[1] => Array
(
[0] => STATIONONE
[1] => 02/22/15 05:00:00 PM
[2] => S
[3] => Array
(
[0] => 2.7
)
[4] => MPH
[5] => Array
(
[0] => 9.61
)
[6] => MPH
)
And it just keeps repeating till I have 23 Values. Then the next station.
So 0-22 subarray value = station 1
23-45 subarray value = station 2
etc.. just stating to help show what I am trying to do.
It isn't entirely clear what you expect your output to be, but this might get you there:
$entriesByStation = []
foreach ($entries as $entry) {
$entriesByStation[$entry[0]] = $entry;
}
This will group all the the entries by station name in the $entriesByStation array
The accepted answer got me close into figuring this out. I had to do this by station though. So I just created 7 foreach statements and created an array for each station. This way I can also merge the array together if needed.
# Parse our All Data and set station
foreach ($array as $entry) {
if ($entry[0] === "STATIONONE"){
$S1pkwsite = ($entry[0]);
$S1pkwvalue = ($entry[5][0]);
$S1pkwdate = ($entry[1]);
$S1pkwunit = ($entry[6]);
$S1wspvalue = ($entry[3][0]);
$S1wspunit = ($entry[4]);
$S1wdrvalue = ($entry[2]);
$S1pkwdataarray[] = array('SiteName'=>$S1pkwsite,'DATE'=>$S1pkwdate,'WDR'=>$S1wdrvalue,'VALUE'=>$S1pkwvalue,'UNIT'=>$S1pkwunit);
}
}
array_push ($Stationone_data, $pkwdataarray);
$Stationone_data = array_shift($Stationone_data);
I'm trying to access a piece of data in an array of arrays that (I believe) is in an object (this may not be the right term though).
When I do print_r on this: $order_total_modules->process() I get...
Array (
[0] => Array (
[code] => ot_subtotal
[title] => Sub-Total:
[text] => $49.99
[value] => 49.99
[sort_order] => 1
)
[1] => Array (
[code] => ot_total
[title] => Total:
[text] => $0.00
[value] => 0
[sort_order] => 12
)
)
If I run echo $order_total_modules->process()[1][3];, I should get "0", because that is the 3rd element of the 2nd array... right? Yet, I get an error.
Can anyone help with this?
Even though it is the third element counting from 0, the index is not 3 it is an associative array with the index value:
Available in PHP >=5.4.0:
echo $order_total_modules->process()[1]['value'];
Or PHP < 5.4.0:
$result = $order_total_modules->process();
echo $result[1]['value'];
You cannot access an associative array via an integer index(unless the index is an actial integer).
So in this case use :
[1]['code'] to access what woulde be [1][0] with a 'normal' array.
Try putting it in a var first:
$ar = $order_total_modules->process();
echo $ar[1]['value'];
The second level array is an assoc, which means that the key is not numeric, which means that you need to call the name of the key, hence the 'value'.
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']).