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>
Related
This question already has answers here:
Looping a multidimensional array in php
(3 answers)
Closed last year.
Here is an array from which I need to sort out the dept name, the full name and the salary , whose salary are above 10000rs.
The array is:
Array
(
[PHP] => Array
(
[0] => Array
(
[name] => Jay
[salary] => 8000
)
[1] => Array
(
[name] => Raj
[salary] => 15000
)
[2] => Array
(
[name] => Mihir
[salary] => 12000
)
)
[Flex] => Array
(
[0] => Array
(
[name] => Vijay
[salary] => 14000
)
)
[System] => Array
(
[0] => Array
(
[name] => Kishan
[salary] => 5000
)
)
)
I am totally confused inside the loops of foreach and don't know how to call each value from the array.
My code allows me to display only names.
Can i know what is the best way to print and work with multidimensional arrays in PHP.
My code:
foreach($newArray as $x=>$x_value){
foreach ($x_value as $y=> $y_value){
if($y_value['salary']>10000)
echo $y_value['name']." has ". $y_value['salary']. ", ";
}
}
Use the following, Tested and working
$filterArray = array();
$i = 0;
foreach($salary as $dept => $employee){
foreach($employee as $index => $data){
if($data['salary'] > 10000){
$filterArray[$i]['deprtment'] = $dept;
$filterArray[$i]['name'] = $data['name'];
$filterArray[$i]['salary'] = $data['salary'];
}
$i++;
}
}
Result :-
Array
(
[1] => Array
(
[deprtment] => PHP
[name] => Raj
[salary] => 15000
)
[2] => Array
(
[deprtment] => PHP
[name] => Mihir
[salary] => 12000
)
[3] => Array
(
[deprtment] => Flex
[name] => Vijay
[salary] => 14000
)
)
Your input is nested array. So you have to use foreach +for loop:
$final_array = array();
foreach($newArray as $x=>$x_value)
{
foreach ($i=0;$i<count($x_value);$i++)
{
if($x_value[$i]['salary']>10000)
{
if(isset($final_array[$x]))
{
array_push($final_array[$x],array("name"=>$x_value[$i]['name'],"salary"=>$x_value[$i]['salary']));
}
else
{
$final_array[$x] = array();
array_push($final_array[$x],array("name"=>$x_value[$i]['name'],"salary"=>$x_value[$i]['salary']));
}
}
}
}
$final_array print dep wise name & salary which is max than 10000
Output :
Array
(
[PHP] => Array
(
[0]=> Array
(
[name] => Raj
[salary] => 15000
)
[1]=> Array
(
[name] => Mihir
[salary] => 12000
)
)
[Flex] => Array
(
[0]=> Array
(
[name] => Vijay
[salary] => 14000)
)
)
)
Here is a simpler solution for looping over the arrays.
foreach ($bigArray as $department => $employees) {
foreach ($employees as $employee) {
if ($employee["salary"] > 10000) {
echo "Department: " . $department;
echo "Employee: " . $employee;
echo "Salary: " . $salary;
} else {
echo $person . " has no money.";
}
}
}
This will output what you were trying to print in your example.
Output for the first employee:
Department: <department name>
Employee: Raj
Salary: 15000
In the future, you should include the department names in your example array since your example doesn't have all of the information you are trying to print; we can't print something that doesn't exist.
I don't know, if i've got you correctly, but if you need to filter out all the people from the sub-arrays (PHP, Flex, System, ...) and then sort them either by their name or salary, you could do it in this or a similar way:
$array = [
'PHP' => [
[
'name' => 'Jay',
'salary' => 8000
],
[
'name' => 'Raj',
'salary' => 15000
],
[
'name' => 'Mihir',
'salary' => 12000
]
],
'Flex' => [
[
'name' => 'Vijay',
'salary' => 14000
]
],
'System' => [
[
'name' => 'Kishan',
'salary' => 5000
]
]
];
$array_people = [];
$array_sorted = [];
$sort_by = 'name'; // Array key name
$sort_desc = false;
$min_salary = 10000;
foreach ($array as $type => $people)
{
foreach ($people as $info)
{
if ($info['salary'] >= $min_salary) {
$array_sorted[] = $info[$sort_by];
$array_people[] = $info;
}
}
}
if ($sort_desc) {
// Sort descending
arsort($array_sorted);
} else {
// Sort ascending
asort($array_sorted);
}
$array_final = [];
foreach (array_keys($array_sorted) as $index)
{
$array_final[] = $array_people[$index];
}
print_r($array_final);
Output:
Array
(
[0] => Array
(
[name] => Mihir
[salary] => 12000
)
[1] => Array
(
[name] => Raj
[salary] => 15000
)
[2] => Array
(
[name] => Vijay
[salary] => 14000
)
)
The first thing you need to do, is to process the main array in a way, that allows you to keep just the items you want - this items need to be stored in a different (empty) array (in this case $array_people).
While detecting the items you need, you've to get out all the values you want to sort by - this can be done at the same time. It's just about creating a new array which will contain just the values you will sort by (in this case $array_sorted).
Then comes the easier part. The next thing to do is sorting the array. There exist a bunch of functions, that can help you with this.
The functions i've used (asort and arsort) are keeping the original key of the item, so you can sort the array containing all the people by the keys of the sorted array (see the code up above).
And that's all, now you have an array with filtered and sorted people :) ... hope, this helps you.
Okay after reading so many solutions I personally believe that some of them are totally confusing for a newbie so here is the solution I actually implemented which is totally simple and easy to understand the flow of multi-dimensional array.
foreach($newArray as $x=>$x_value){
foreach ($x_value as $y=> $y_value){
if($y_value['salary']>10000){
echo "<tr>";
echo "<td>"; echo $y_value['name']; echo "</td>";
echo "<td>"; echo $x; echo "</td>";
echo "<td>"; echo $y_value['salary']; echo "</td>";
echo "</tr>";
}
}
}
The output will be like, (if u use table )
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 which is
Array ( [0] => Array ( [picture] => 5a55ed8d8a5c8910913.jpeg
[id] => 1284
[price_range] => Rs 12000 - 9000
[name] => Brown Beauty Office Chair )
[1] => Array ( [picture] => 5a55eefeb9a8e255836.jpeg
[id] => 1285
[price_range] => Rs 8989 - 7000
[name] => Chang Series Office Chair (Grey)
)
)
Now I am fetching the value of id on clicking a remove button, the value I fetch is 1284.
I want to take out just [id]=> 1284 from the above array and then display it using a foreach loop. How I can delete just the [id]=> 1284 without disturbing the other id values and other element.
In the above array I would like to delete one particular id value say just the [id]=> 1284 and keep all other elements intact and as it is.
Any help is welcome.
Use array_search and array_column, to find by id and remove by unset method,
<?php
$array = [
["id"=>123,"desc"=>"test1"],
["id"=>456,"desc"=>"test2"],
["id"=>789,"desc"=>"test3"],
];
$id = 456;
$index = array_search($id, array_column($array, 'id'));
unset($array[$index]);
print_r($array);
?>
Live Demo
Array
(
[0] => Array
(
[id] => 123
[desc] => test1
)
[2] => Array
(
[id] => 789
[desc] => test3
)
)
Since you asked how to achieve it using foreach, I came up with this.
$array = Array (Array ( 'picture' => '5a55ed8d8a5c8910913.jpeg','id' => 1284,'price_range' => 'Rs 12000 - 9000', 'name' => 'Brown Beauty Office Chair'),
Array ( 'picture' => '5a55eefeb9a8e255836.jpeg','id' => 1285,'price_range' => 'Rs 8989 - 7000','name' => 'Chang Series Office Chair (Grey)')
);
foreach($array as $key => $val) {
$id = $array[$key]['id'];
if($id === 1284){
unset($array[$key]['id']);
}
}
print_r($array)
?>
You can also use this too:
<?php
$element_to_remove = 1284;
$i = 0;
foreach($array as $this_arr){
$index = array_search($element_to_remove, $this_arr);
//unset($this_arr[$index]); this formate does not remove element from array
//but below works fine
if(isset($array[$i][$index])){
unset($array[$i][$index]);
}
}
print_r($array);
?>
I need to display a certain object from an array before showing the rest of the array.
The array looks like this:
Array
(
[0] => stdClass Object
(
[template_id] => 91
[template_name] => Alphabet
[template_thumbnail] => blank-template-thumbnail.jpg
[template_create_date] => 1456821665
[template_customer_id] => 0
[template_is_responsive] => no
[template_type] => builder
[template_category] => simple
[sort] => 2
)
[1] => stdClass Object
(
[template_id] => 92
[template_name] => Blank Template
[template_thumbnail] => blank-template-thumbnail.jpg
[template_create_date] => 1456821670
[template_customer_id] => 0
[template_is_responsive] => no
[template_type] => builder
[template_category] => simple
[sort] => 2
)
[2] => stdClass Object
(
[template_id] => 31
[template_name] => Holiday Specials
[template_thumbnail] => accommodation-1-20110926.jpg
[template_create_date] => 1456821660
[template_customer_id] => 0
[template_is_responsive] => no
[template_type] => builder
[template_category] => Accommodation
[sort] => 3
)
)
I need to show Blank Template first and then show the rest alphabetically (the order it is in now.
Is there a more elegant solution than looping through the array twice? The size of the array can be anything from 1 (the blank template) to countless objects.
$str="";
for($i=0;$i<=count($arr);$i++){
if($arr[$i]['template_name'] == "Blank Template"){
echo $arr[$i]['template_name'];
}else{
$str .= $arr[$i]['template_name']. "<br>";
}
}
echo $str;
Try this:
$firstItem = null;
$outArray = [];
foreach($yourArray as $item){
if($item->template_name == 'Blank Template'){
$firstItem = $item;
}else{
$outArray[$item->template_name] = $item;
}
}
ksort($outArray,SORT_STRING);
array_unshift($outArray,$firstItem);
Just one loop. Pay attention that this way of doing things, just work if you have uniqueness on the template_name!
Hope it helps.
This will work for you, try
<?php
$dataArray = array(0=>array('template_id'=>91,'template_name'=>'Alphabet'),
1=>array('template_id'=>92,'template_name'=>'Blank Template'),
2=>array('template_id'=>31,'template_name'=>'Holiday Specials')
);
$newArray = array();
foreach($dataArray as $key => $val)
{
if(in_array('Blank Template',$val))///find the key for black template
{
unset($dataArray[$key]); ///unset black temp from original array
$newArray[] = $val;///push black temp into new array at 0 index
foreach($dataArray as $k => $v)
{
$newArray[] = $v; ///push the renaming values into new array
}
}
}
echo "<pre>"; print_r($newArray);
?>
This will give you :
Array
(
[0] => Array
(
[template_id] => 92
[template_name] => Blank Template
)
[1] => Array
(
[template_id] => 91
[template_name] => Alphabet
)
[2] => Array
(
[template_id] => 31
[template_name] => Holiday Specials
)
)
LIVE EXAMPLE : CLICK HERE
I have array like this. This array is created dynamically
Array
(
[Data NotUploading] => Array
(
[items] => Array
(
[0] => Array
(
[date] => 2013-04-02
[issue_id] => 1
[phone_service_device] => A
[phone_service_model] =>
[phone_service_os] =>
[phone_service_version] =>
[issue_name] => Data NotUploading
)
[1] => Array
(
[date] => 2013-04-02
[issue_id] => 1
[phone_service_device] => I
[phone_service_model] =>
[phone_service_os] =>
[phone_service_version] =>
[issue_name] => Data NotUploading
)
)
)
[Battery Problem] => Array
(
[items] => Array
(
[0] => Array
(
[date] => 2013-04-03
[issue_id] => 3
[phone_service_device] => I
[phone_service_model] =>
[phone_service_os] =>
[phone_service_version] =>
[issue_name] => Battery Problem
)
)
)
)
What I need to do is to use 2 foreach or 1 foreach & 1 for loop so that I can get each value of date I did like this
foreach($gResultbyName as $key1 => $rec){
for($j = 0;$j<count($rec);$j++ ){
echo $rec['items'][$j]['date'];
}
}
but its only retrieving 2013-04-02 & 2013-04-03 that is 0 index date of data NotUploading & 0 index date of Battery Problem. Basically I need to compare each value and others stuff but I just cant get each date value.
Forgive me for ignorance but I tried a lot :(
try this:
foreach ($data as $d)
{
foreach($d['items'] as $item)
{
echo $item['date'];
}
}
Your for-loop loops count($rec) times, but should count($rec['items']).
This should load the dates into an array sorted by the issue_name. The you can step through them for further processing.
$dates= array();
foreach ($gResultbyName AS $events){
foreach ($events['items'] AS $item){
$dates[$item['issue_name']][] = $item['date'];
}
}
var_dump($dates);