Im struggling with displaying the country_name, country_prefix followed by the city_name and city_prefix to display in PHP
Array (
[0] => stdClass Object
(
[country_name] => Russian Federation
[country_prefix] => 7
[country_iso] => RU
[cities] => Array
(
[0] => stdClass Object
(
[city_id] => 107
[city_name] => Moscow
[city_prefix] => 495
[city_nxx_prefix] =>
[setup] => 0
[monthly] => 60.9
[isavailable] => 1
[islnrrequired] => 0
)
...
This above returns the $results array and Im currently using something like this but have tried many iterations.
echo '<br />Results: <br />';
foreach($result as $countries => $country) {
foreach($country as $details => $value) {
echo $value . "<br/>";
}
}
Try this:
foreach($results as $country){
// country name in $country->country_name
foreach($country->cities as $city){
echo $city->city_name.'<br/>';
}
}
As you've been told in comments, you have an array of objects. You can iterate it with foreach, but then you should access its properties using the proper syntax (->)
Related
i'm parsing a json file (api rest) but i can't solve a problem. This is the json file.
Array
(
[110197275197292] => Array
(
[mid] => 110197275197292
[home] => FC Den Bosch
[away] => SC Telstar
[country_leagues] => Netherlands - Eerste Divisie
[leagues] => Eerste Divisie
[country] => Netherlands
[score] =>
[home_score] => 0
[away_score] => 0
[periodID] =>
[periodTXT] =>
[periodTime] => 1632923759
[startTime] => 1633111200
[lastUpdateTime] => 1632923357
[minutes] => 0
[status] => 1
[importancy] => 281
[odds] => Array
(
[home] => 2.45
[draw] => 3.70
[away] => 2.40
[1st-1] => 2.90
[1st-0] => 2.35
[1st-2] => 2.87
[2nd-1] => 2.70
[2nd-0] => 2.70
[2nd-2] => 2.65
with this code below i print the value of the array, and work.
foreach ($response as $key1 => $value1){
echo $response[$key1]['home'] .'<br>';
}
Now i would insert the value of the array in a variable, something like that
foreach ($response as $key1 => $value1){
$prova = $response[$key1]['home'];
}
<?php echo $prova; ?>
This way I could recall it in an html table. This code print me only one value of the array and does not loop (foreach). The value that prints in this case is Nashville SC which is a value found in the json file. Where is my mistake? there is a way to encapsulate array values in a variable and then recall it later in the html code?
You are always overwriting the $prova variable with the home team. You should either convert $prova to an array and work with it or move the echo inside your loop to print everything.
Moreover you should use more distinct names to your variables so both we and you understand your code.
//1. echo way
foreach ($response as $matchDate => $matchData){
$prova = $matchData['home'];
echo $prova;
}
//2. array way
$prova = [];
foreach ($response as $matchDate => $matchData){
$prova[$matchDate] = $matchData['home'];
}
var_dump($prova); //This will print the whole array of home teams.
I have this Array but i don't know how to get the [discount_amount] based on the [object_ids].
For example i would like to get the 93 value if my [object_ids] contain 81.
Array
(
[0] => Array
(
[id] => rule_5b0d40cd1408a
[membership_plan_id] => 106
[active] => yes
[rule_type] => purchasing_discount
[content_type] => post_type
[content_type_name] => product
[object_ids] => Array
(
[0] => 81
)
[discount_type] => amount
[discount_amount] => 93
[access_type] =>
[access_schedule] => immediate
[access_schedule_exclude_trial] =>
)
[1] => Array
(
[id] => rule_5b0d4e0f3b0b4
[membership_plan_id] => 106
[active] => yes
[rule_type] => purchasing_discount
[content_type] => post_type
[content_type_name] => product
[object_ids] => Array
(
[0] => 110
)
[discount_type] => amount
[discount_amount] => 50
[access_type] =>
[access_schedule] => immediate
[access_schedule_exclude_trial] =>
)
)
You could use a foreach and use in_array to check if the array object_ids contains 81.
foreach ($arrays as $array) {
if (in_array(81, $array["object_ids"])) {
echo $array["discount_amount"];
}
}
Demo
Try with this code .
Assuming $dataArray is the array you have printed.
foreach ($dataArray as $key => $value){
if($value['object_ids'][0] == 83){
$discount_amount = $value['discount_amount'];
}
}
echo $discount_amount
The way I mostly do this is as followed:
# Save retrieved data in array if you want to.
$test = array();
foreach($array as $line){
# Count the row where discount_amount is found.
$test[] = $line['9'];
echo "Result: ".$line['9']. "<br \>\n";
# OR another method is
$test[] = $line['discount_amount'];
echo "Result: ".$line['discount_amount']. "<br \>\n";
}
I have an array like
Array
(
[0] => stdClass Object
(
[id] => 1
[org_name] => name
[field_name] => fullname
[new_name] => Name
[index] => 3
[modified] => 2016-05-17 10:45:17
)
[1] => stdClass Object
(
[id] => 3
[org_name] => reception_no
[field_name] => reception_no
[new_name] => Reception No.
[index] => 1
[modified] => 2016-05-17 10:45:17
)
[2] => stdClass Object
(
[id] => 4
[org_name] => pno
[field_name] => pno
[new_name] => Personel No.
[index] => 0
[modified] => 2016-05-17 10:45:17
)
and i want for example
where object has 'pno' get value of 'index' in this example for example '0'
is there possible to do that ?
foreach ($arr as $items)
{
if ($items->org_name=='pno')
$index=$items->index;
}
As i am asking you about the pno, I think it was the first index like 0,1,2..., But after some conversation this is clear that it is inside the sub array.
So you need a loop here and check for the pno, if matched then echo the index. Let your array is $array
foreach ($array as $key => $val){
if($val->org_name == 'pno'){
echo $index = $val->index;
break;
}
}
yes it is possible try this
var_dump($arr[0]->index);
OR
print_r($arr->index['0']);
You can use array_search
$key1 = array_search('pno', array_column($your_array, 'field_name'));
$key2 = array_search('pno', array_column($your_array, 'org_name'));
Use array_search since you may not know the index
array_search
Tested with ur Array
$array = array(
array('id'=>1,'org_name'=>'name','field_name'=>'fullname','new_name'=>'Name','index'=>3,'modified'=>'2016-05-17 10:45:17'),
array('id'=>3,'org_name'=>'reception_no','field_name'=>'reception_no','new_name'=>'Reception No.','index'=>1,'modified'=>'2016-05-17 10:45:17'),
array('id'=>4,'org_name'=>'pno','field_name'=>'pno','new_name'=>'Personel No.','index'=>0,'modified'=>'2016-05-17 10:45:17')
);
This Code should do what u want
$index = '';
foreach($array as $key => $value)
{
if($value['org_name']=='pno')
{
$index = $value['index'];
}
}
print $index;
Script only Loops through ur Array and sets $index on the last found pno index value
U can check $index in an IF, if ist empty.
I am using the Google Analytics V3 PHP OAuht API. When using Simple.php in Google Analytics API Example the data are returned as PHP arrays. I am using the following call to get a more detailed answer to some specific data. It works fine.
$ids = "ga:xxxxxx";
$start_date = "2011-01-01";
$end_date = "2011-11-30";
$metrics = "ga:visits,ga:pageviews";
$dimensions = "ga:browser";
$optParams = array('dimensions' => $dimensions);
$data = $service->data_ga->get($ids,$start_date,$end_date,$metrics,$optParams);
Output of the Array is
Data
Array
(
[kind] => analytics#gaData
[id] => https://www.googleapis.com/analytics/v3/data/ga?ids=ga:xxxxxxx&dimensions=ga:browser&metrics=ga:visits,ga:pageviews&start-date=2011-01-01&end-date=2011-11-30&start-index=1&max-results=1000
[query] => Array
(
[start-date] => 2011-01-01
[end-date] => 2011-11-30
[ids] => ga:xxxxxxxx
[dimensions] => ga:browser
[metrics] => Array
(
[0] => ga:visits
[1] => ga:pageviews
)
[start-index] => 1
[max-results] => 1000
)
[itemsPerPage] => 1000
[totalResults] => 220
[selfLink] => https://www.googleapis.com/analytics/v3/data/ga?ids=ga:xxxxx&dimensions=ga:browser&metrics=ga:visits,ga:pageviews&start-date=2011-01-01&end-date=2011-11-30&start-index=1&max-results=1000
[profileInfo] => Array
(
[profileId] => xxxxx
[accountId] => xxxxx
[webPropertyId] => UA-xxxxxx-x
[internalWebPropertyId] => xxxxxxxxxx
[profileName] => xxxxx.com
[tableId] => ga:xxxxxxxx
)
[containsSampledData] =>
[columnHeaders] => Array
(
[0] => Array
(
[name] => ga:browser
[columnType] => DIMENSION
[dataType] => STRING
)
[1] => Array
(
[name] => ga:visits
[columnType] => METRIC
[dataType] => INTEGER
)
[2] => Array
(
[name] => ga:pageviews
[columnType] => METRIC
[dataType] => INTEGER
)
)
[totalsForAllResults] => Array
(
[ga:visits] => 36197
[ga:pageviews] => 123000
)
[rows] => Array
(
[0] => Array
(
[0] => (not set)
[1] => 459
[2] => 1237
)
[1] => Array
(
[0] => 12345
[1] => 3
[2] => 3
)
[2] => Array
(
[0] => 440955
[1] => 1
[2] => 1
)
[3] => Array
(
[0] => Alexa Toolbar
[1] => 1
[2] => 1
)
[4] => Array
(
[0] => Android Browser
[1] => 4177
[2] => 9896
)
....
The [Rows] Array has 219 entries.
Now the problem. I have spent the last week trying to parse this into an HTML table or anything that looks presentable. I have come close, but it seems this multi-dimensional array is beyond what I am able to handle. I am also trying to keep the solution flexible enough to handle more metrics or dimensions if they are added as well. I am self-taught PHP, so maybe I am missing a function or two that could make this easier. Thanks again for any hints, tips of ideas to make this work.
I got a bit further, but I does not fully format the way I want...maybe someone can see where I went wrong
$output = $service->data_ga->get($ids,$start_date,$end_date,$metrics,$optParams);
echo'<table style="text-align: left; width: 100%;" border="1" cellpadding="2"
cellspacing="2">
<tbody><tr>';
foreach ($output['columnHeaders'] as $header) {
print "<td>";
printf('%25s', $header['name']);
print "</td>";
}
print "</tr>";
foreach ($output['rows'] as $row) {
print "<td>";
foreach ($row as $column)
printf('%25s', $column);
print "</td>";
}
print "\n";
echo'
</tbody>
</table>';
I still can't seem to get the rows to display right.
To get you on your way use
$data [rows][$i][$j][columnHeaders] [0][name]
$data [rows][$i][$j][columnHeaders] [1][name]
and for rows use something like
$data [rows][0][1]
You will have to get the variable via increment with something like:
var =(count($data [columnHeaders]));
for ($i='0'; $i<=$var; $i++) {
echo '.$data [columnHeaders] [$i][name].';}
This should get you on your way towards building your table. Good Luck!
The issue is in your foreach for the table body rows. You appear to have missed the rows out. Wrap it in another loop to print out tr around the set of tds.
This is what I used for printing out a table of analytics data:
$data = $analytics->data_ga->get('ga:' . $profileId, $dateFrom, $dateTo, $metrics, array('dimensions' => $dimensions));
<table>
<thead>
<tr>
<?php
foreach ($data->columnHeaders as $header) {
$headerName = ucwords(preg_replace('/(\w+)([A-Z])/U', '\\1 \\2', str_replace('ga:', '', $header->name)));
print '<th>';
printf('%s', $headerName);
print '</th>';
}
?>
</tr>
</thead>
<tbody>
<?php
foreach ($data->rows as $row) {
print '<tr>';
foreach ($row as $cell) {
print '<td>';
printf('%s', $cell);
print '</td>';
}
print '</tr>';
}
?>
</tbody>
</table>
I am trying to read out this nested array with a foreach loop but get an error "invalid argument supplied in foreach"
Array (
[regenerated] => 1302668837
[id] => 2
[qty] => 1
[price] => 1200
[name] => support
[optione] =>
[cart_contents] => Array (
[c4ca4238a0b923820dcc509a6f75849b] => Array (
[rowid] => c4ca4238a0b923820dcc509a6f75849b
[id] => 1
[qty] => 1
[price] => 29.95
[name] => Training DVD
[optione] =>
[subtotal] => 29.95
)
[c81e728d9d4c2f636f067f89cc14862c] => Array (
[rowid] => c81e728d9d4c2f636f067f89cc14862c
[id] => 2
[qty] => 1
[price] => 1200
[name] => support
[optione] =>
[subtotal] => 1200
)
[total_items] => 2
[cart_total] => 1229.95
)
[johndoe] => audio
[totalItems] => 2
)
$cart_contentz = $_SESSION['cart_contents'];
foreach($cart_contentz as $itemz => $valuez) {
foreach($valuez as $key1 => $value1) {
echo "$key1: $value1<br>";
}
the first level of your main array has items that are sub-arrays and some that are not. Your second loop doesn't work on non-array items.
Thus, your code should be:
foreach($cart_contentz as $itemz => $valuez) {
if (is_array($valuez)) {
foreach($valuez as $key1 => $value1) {
echo "$key1: $value1<br>";
}
} else {
echo "$itemz: $valuez<br>";
}
}
you'll need to load that array into your $_SESSOIN['cart_contents'] which may have been done. secondly, your inner foreach is acting on the values of that array which are not arrays. I'm fairly certain that the inner foreach is causing your woes. Also, your Array may just be for illustrating what's in $_SESSION['cart_contents'], but adding quotation marks instead of square brackets around the keys will make it more uniform and easier to read.
Update:
after seeing the reformatted code, thanks #AgentConundrum, now I can more clearly see the issue. Try adding an if(is_array($valuez)) around your inner foreach.
Maybe to use recursion:
function printArray($array, $parent=false, $level=0) {
if (!($parent === false)) echo "<b>".str_pad('',($level-1)*4,"-")."[$parent] =></b><br />\n";
foreach ($array as $key=>$value) {
if (!is_array($value)) echo str_pad('',$level*4,"-")."[$key] => $value<br />\n";
else printArray($value, $key, $level+1);
}
}
print_array($your_array);