Array with php for Json output - php

i'm trying to get the best practice to manipulate my array to get a json in a format similar to this one (better to work with charts)
{
"serieMonth":["Aug-12","Sep-12","Oct-12","Nov-12","Dec-12","Jan-13","Feb-13"],
"serieCA":[4214,10119,13325,12818,7177,20628,7664],
"serieAdwordsCA":[0,0,0,0,0,310,332],
"serieBooking":[10,28,46,34,17,51,16],
"serieAdwords":[0,0,0,0,0,1,1],
"serieTotalBooking":[10,28,46,34,17,52,17],
"serieCartRepartition":[421,361,290,377,422,397,451],
"serieTotalCart":[421,361,290,377,422,397,451]
}
Actually my output looks like this :
[
{"date_year":"2012","date_month":"08","ad_cost":"0.0","ad_clicks":"0"},
{"date_year":"2012","date_month":"09","ad_cost":"0.0","ad_clicks":"0"},
{"date_year":"2012","date_month":"10","ad_cost":"0.0","ad_clicks":"0"},
{"date_year":"2012","date_month":"11","ad_cost":"0.0","ad_clicks":"0"},
{"date_year":"2012","date_month":"12","ad_cost":"44.9","ad_clicks":"43"},
{"date_year":"2013","date_month":"01","ad_cost":"297.56","ad_clicks":"462"},
{"date_year":"2013","date_month":"02","ad_cost":"82.5","ad_clicks":"103"}
]
And I'm using javascript to change it :
var xAxisLabels = new Array(),
adClicks = new Array(),
adCost = new Array();
$.each(data, function(i,v) {
xAxisLabels.push(v["date_month"]+'/'+v["date_year"]);
adCost.push(parseInt(v["ad_cost"]));
adClicks.push(parseInt(v["ad_clicks"]));
});
I'm looking for the best way to do it in php since I get this data by the google api, here is my php.
// dimensions
$dimensions = 'ga:year,ga:month';
$_params[] = 'date_year';
$_params[] = 'date_month';
// metrics
$metrics = 'ga:adCost,ga:adClicks';
$_params[] = 'ad_cost';
$_params[] = 'ad_clicks';
$response = $service->data_ga->get('ga:' . $projectId, $from, $to, $metrics, array('dimensions' => $dimensions));
$analyticsStats = array();
foreach ($response['rows'] as $row) {
$dataRow = array();
foreach ($_params as $colNr => $column) {
$dataRow[$column] = $row[$colNr];
}
array_push($analyticsStats, $dataRow);
}

You can build an array of arrays then add items the the sub-arrays in a loop:
$output = array(
"serieMonth" => array(),
"serieCA" => array(),
"serieAdwordsCA" => array(),
"serieBooking" => array(),
"serieAdwords" => array(),
"serieTotalBooking" => array(),
"serieCartRepartition" => array(),
"serieTotalCart" => array()
);
foreach($response["rows"] as $row) {
$output["serieMonth"][] = date("Y-M", strtotime("{$row['date_year']}-{$row['date_month']}-01"));
$output["serieCA"][] = $row["ad_cost"];
$output["serieAdwordsCA"][] = $row["ad_clicks"];
// etc...
}
echo json_encode($output);

Related

PHP Horde imap how to fetch

I saw the similar questions, but it has not helped me. I am trying to fetch message. I need full message with all parts, headers, attachments.
$fetchQuery = new Horde_Imap_Client_Fetch_Query();
$fetchQuery->fullText();
/** #var Horde_Imap_Client_Fetch_Results $mail */
$results = $client->fetch('INBOX', $fetchQuery, ['ids' => new Horde_Imap_Client_Ids(11632)]);
var_dump($results->first()->getEnvelope()->subject);
I tried a lot of variants. But I can't get any info about message. The subject is empty string. I am sure, such mail with that uid exists, I got this uid with Horde also.
Try the code mentioned below. $results array has all the items you need.
$uids = new \Horde_Imap_Client_Ids($thread_uids);
$query = new \Horde_Imap_Client_Fetch_Query();
$query->envelope();
$query->structure();
$messages = $oClient->fetch($mailbox, $query, array('ids' => $uids));
$results = [];
foreach($messages as $message){
$envelope = $message->getEnvelope();
$structure = $message->getStructure();
$msghdr = new StdClass;
$msghdr->recipients = $envelope->to->bare_addresses;
$msghdr->senders = $envelope->from->bare_addresses;
$msghdr->cc = $envelope->cc->bare_addresses;
$msghdr->bcc = $envelope->bcc->bare_addresses;
$msghdr->subject = $envelope->subject;
$msghdr->timestamp = $envelope->date->getTimestamp();
$query = new Horde_Imap_Client_Fetch_Query();
$query->fullText();
$typemap = $structure->contentTypeMap();
foreach ($typemap as $part => $type) {
// The body of the part - attempt to decode it on the server.
$query->bodyPart($part, array(
'decode' => true,
'peek' => true,
));
$query->bodyPartSize($part);
}
$id = new Horde_Imap_Client_Ids($message->getUid());
$messagedata = $oClient->fetch($mailbox, $query, array('ids' => $id))->first();
$msgdata = new StdClass;
$msgdata->id = $id;
$msgdata->contentplain = '';
$msgdata->contenthtml = '';
$msgdata->attachments = array(
'inline' => array(),
'attachment' => array(),
);
$plainpartid = $structure->findBody('plain');
$htmlpartid = $structure->findBody('html');
foreach ($typemap as $part => $type) {
// Get the message data from the body part, and combine it with the structure to give a fully-formed output.
$stream = $messagedata->getBodyPart($part, true);
$partdata = $structure->getPart($part);
$partdata->setContents($stream, array('usestream' => true));
if ($part == $plainpartid) {
$msgdata->contentplain = $partdata->getContents();
} else if ($part == $htmlpartid) {
$msgdata->contenthtml = $partdata->getContents();
} else if ($filename = $partdata->getName($part)) {
$disposition = $partdata->getDisposition();
$disposition = ($disposition == 'inline') ? 'inline' : 'attachment';
$attachment = new StdClass;
$attachment->name = $filename;
$attachment->type = $partdata->getType();
$attachment->content = $partdata->getContents();
$attachment->size = strlen($attachment->content);
$msgdata->attachments[$disposition][] = $attachment;
}
}
$data = [
'uid' => implode("",$id->ids),
'from' => implode(",",$msghdr->senders),
'cc' => implode(",",$msghdr->cc),
'bcc' => implode(",",$msghdr->bcc),
'to' => implode(",",$msghdr->recipients),
'date' => $msghdr->timestamp,
'subject' => $envelope->subject,
'hasAttachments' => $structure->getDisposition(),
'folder' => $mailbox,
'messageId' => $envelope->message_id,
'attachment' => $msgdata->attachments
];
$data['body'] = empty($msgdata->contenthtml) ? $msgdata->contenttext: $msgdata->contenthtml;
array_push($results,$data);
}
$fetchQuery = new Horde_Imap_Client_Fetch_Query();
$fetchQuery->fullText();
/** #var Horde_Imap_Client_Fetch_Results $mail */
$results = $client->fetch('INBOX', $fetchQuery, ['ids' => new Horde_Imap_Client_Ids(11632)]);
var_dump($results->first()->getFullMsg());

Convert MySQL result to XML format using PHP with multidimensional array

I am trying to get my XML format be like this:
but my code now does not loop for the 'order_line' array and will return like this:
below are sample of my code I did:
$result = $this->db->query("SELECT * FROM `grn_order` a");
foreach($result->result() as $row )
{
$result_line = $this->db->query("SELECT * FROM `grn_order_line` a where a.order_no = '$row->order_no'");
foreach($result_line->result() as $row_line);
{
$line = array(
'guid' => $row_line->guid,
'itemcode' => $row_line->itemcode,
);
}
$my_array[] = array(
'order_no' => $row->order_no,
'loc_code' => $row->loc_code,
'trans_code' => $row->trans_code,
'po_no' => $row->po_no,
'order_line' => $line
);
} $xml = new SimpleXMLElement('<orders/>');
// function callback
$data = $this->array2XML($xml, $my_array);
print $xml->asXML();
function array2XML($obj, $array)
{
foreach ($array as $key => $value)
{
if(is_numeric($key))
$key = 'order';
if (is_array($value))
{
$node = $obj->addChild($key);
$this->array2XML($node, $value);
}
else
{
$obj->addChild($key, htmlspecialchars($value));
}
}
}
You keep on overwriting the last line in your load loop. Change it to...
$line = [];
foreach($result_line->result() as $row_line);
{
$line[] = array(
'guid' => $row_line->guid,
'itemcode' => $row_line->itemcode,
);
}
So each line is added using $line[].

Merge duplicate values from array in Json Formate

I am fetching data from location MySql table as structure is below
in my PHP code
I need send Json output in response as below (Table data may not be same as below json data but the format is same)
http://jsoneditoronline.org/?id=7c5600712df6f9ec1f8fbb8a13aba3de
Tried to do the following in the code to convert the array that i fetch from the table but however am unable to get it in the right format
$sql = "SELECT * FROM mobile_user_regions";
$stmt = $this->db->prepare($sql);
$stmt->execute();
$resCArray = $stmt->fetchAll(PDO::FETCH_ASSOC);
$ress = array();
foreach ($resCArray as $key => $value) {
$ress['regions'][] = array(array(
'name' => $value['region'],
'location' => array(
array(
'name' => $value['location'],
'store' => array(
'store_details' => $value['store_details'],
'store_phone' => $value['store_phone'],
'store_email' => $value['store_email'],
'store_latitude' => $value['store_latitude'],
'store_longitude' => $value['store_longitude']
)
)
)
)
);
Output: that i am getting is
**http://jsoneditoronline.org/?id=4d4a75177350e254ceee7238af13f2f7**
$regionArray = $xyzObject->getRegion();
if (!empty($regionArray) && isset($regionArray)) {
$i = 0;
$locationData = array();
foreach ($regionArray as $key => $value) {
$locationData['regions'][$i]['name'] = $value['region'];
$locationArray = $xyzObject->getLocation($value['region']);
$locationData['regions'][$i]['locations'] = $locationArray;
$i++;
}
$j = 0;
foreach ($locationData['regions'] as $key => $regions) {
$k = 0;
foreach ($regions['locations'] as $key1 => $locations) {
$storeArray = $xyzObject->getStore($locations['name']);
$locationData['regions'][$j]['locations'][$k]['stores'] = $storeArray;
$k++;
}
$j++;
}
echo json_encode($locationData);

Zabbix Reading the Api

I'm getting Informations from the Zabbix Api with a PHP library. At the moment I get the "lastvalue" from the json Array:
try {
// connect to Zabbix-API
$api = new ZabbixApi($api_url, $username, $password);
$params = array(
'groupids' => '2',
'real_items' =>TRUE,
'monitored_items' =>TRUE,
'search' => array('name' => 'Disk root used p'),
'selectFunctions' => 'extend',
'output' => 'extend',
'sortfield' => 'name',
'limit' => '1'
);
$trends = $api->itemGet($params); // get data from api
$names = array();
foreach($trends as $trend) { // loop through the returned data
$names[] = $trend->lastvalue;
}
//print_r($names);
} catch(Exception $e) {
// Exception in ZabbixApi catched
echo $e->getMessage();
}
But now I want to get the "lastvalue" plus the "name" of the Item in this Array for example like that: "name"+"lastvalue". How can I get both of them into my array $names[]?
Here is my answer from my comments, hope its what you are looking for!
$trends = $api->itemGet($params);
$names = array();
foreach($trends as $trendKey => $trendValue)
{
$names[$trendKey] = $trendValue;
}
#Test the names array
foreach ($names as $nameKey => $nameValue)
{
print("{$nameKey} = {$nameValue}<br />");
}
Return value:
groupids = 2
real_items = TRUE
...
sortfield = name
limit = 1

Creation of array with results of different xPath::query(s). Improvement?

I don't actually have a problem, however, I am looking to improve my source code. I have three different queries whose results should be combined in an array. An example of the array:
array(
array(
'q0-result' => '...',
'q1-result' => '...',
'q2-result' => '...'
),
array(
'q0-result' => '...',
'q1-result' => '...',
'q2-result' => '...'
)
);
So now I have the following source code, however, I do not like the usage of $idx and how the array is being built. Do you have suggestions to improve the following source code?:
$data = array();
$dom = new DomDocument();
#$dom->loadHTML(file_get_contents('http://www.example.com'));
$xpath = new DomXpath($dom);
$idx = 0;
foreach($xpath->query('query0') as $element) {
$data[$idx]['q0-result'] = $element->nodeValue;
}
$idx = 0;
foreach($xpath->query('query1') as $element) {
$data[$idx]['q1-result'] = $element->nodeValue;
}
$idx = 0;
foreach($xpath->query('query2') as $element) {
$data[$idx]['q2-result'] = $element->nodeValue;
}
var_dump($data);
(If i understood) Do it:
foreach($xpath->query('query0') as $element)
$data['q0-result'][] = $element->nodeValue;
foreach($xpath->query('query1') as $element)
$data['q1-result'][] = $element->nodeValue;
foreach($xpath->query('query2') as $element)
$data['q2-result'][] = $element->nodeValue;
// below chunking in your format
/*
array(
array(
'q0-result' => '...',
'q1-result' => '...',
'q2-result' => '...'
),
array(
'q0-result' => '...',
'q1-result' => '...',
. ......
*/
$out = array();
$row0=array_shift($data['q0-result']);
$row1=array_shift($data['q1-result']);
$row2=array_shift($data['q2-result']);
while($row0 || $row1 || $row2){
$row0 = !empty($row0)? $row0 : null;
$row1 = !empty($row1)? $row1 : null;
$row2 = !empty($row2)? $row2 : null;
$out[] = array('q0-result'=>$row0,'q1-result'=>$row1,'q2-result'=>$row2 );
$row0=array_shift($data['q0-result']);
$row1=array_shift($data['q1-result']);
$row2=array_shift($data['q2-result']);
}
echo '<pre>';
print_r($out);
echo '</pre>';

Categories