Get multidimensional array out of query - php

I am trying to get multidimensional array out of query and for some reasons it does not work.
I use query to retrieve data from mysql.
$sql = "SELECT Id, UserID, TimeAction, Command FROM users_checked WHERE UserId = 4 AND date(TimeAction) = '2016-12-05 '";
$q=$conn->query($sql);
$data = array();
while($r=$q->fetchAll((PDO::FETCH_ASSOC))){
$data[]=$r;
}
Array output
I should get array like printed below
$data = array(
array(
"Id" => "1",
"UserID" => "1",
"TimeAction" => "2016-11-29 08:00:00",
"Command" => "Prijava"
),
array(
"ID" => "1",
"USERID" => "1",
"TimeAction" => "2016-11-29 10:05:14",
"Command" => "Odjava"
),
array(
"Id" => "1",
"UserID" => "1",
"TimeAction" => "2016-11-29 12:22:14",
"Command" => "PoslovniIzlazak"
),
array(
"ID" => "1",
"USERID" => "1",
"TimeAction" => "2016-11-29 13:32:14",
"Command" => "Prijava"
),
array(
"ID" => "1",
"USERID" => "1",
"TimeAction" => "2016-11-29 16:00:00",
"Command" => "Odjava"
),
);

fetchAll - Returns an array containing all of the result set rows where as fetch - Fetches the next row from a result set.
So you have to use fetch instead of fetchAll if you want the data row wise.
Try this code.
while ($r = $q->fetch(PDO::FETCH_ASSOC))
{
$data[] = $r;
}
Reference:
fetch
fetchAll

You should probably use fetch_assoc() instead of fetch_all in your for loop, this way you can push the data you want into your array for each row of your mysql query result.
It would look like this :
$data = array();
while ($row = $r->fetch_assoc()) {
$row_array = array(
"Id" => row['Id'],
"UsedID" => row['UserID'],
"TimeAction" => row['TimeAction'],
"Command" => row['Command']
);
array_push($data, $row_array);
}
Please note I didn't test the code, I'm doing this by head.
Also, I'm guessing you didn't mean to write all Ids to "1" in your example.

Related

How to get data from JSON file by parsing array name from the url

I am trying to print data in json format from my 'data.json' file. With my php file (alldata.php), I could get all data (arrays) pretty printed. But where I want you to help me is how to get a specific array name and it objects/content.
My alldata.php looks like this:
{
"players": [
{
"name": "Marcos Alonso",
"position": "Left-Back",
"nationality": "Spain",
"marketValue": "9,000,000 €",
"created": "2017-04-15 10:04:58"
}],
"articles": [
{
"author": "Stephen Walter",
"title": "Disruptive stag party revellers thrown off plane at Manchester Airport",
"url": "http://www.telegraph.co.uk/news/2017/04/15/disruptive-stag-party-revellers-thrown-plane-manchester-airport/",
"publishedAt": "2017-04-15T09:25:10Z"
}],
land": [
{
"state": "Somewhr",
"found": "1889",
"area": "6,812",
"empl": "1,325",
"ppl": "16,842"
}]
}
In php, how can I get an array e.g "players" with the content by using url such as 'alldata.php?search=players'
Here is a code sample....
//get content of the JSON API using file_get_contents()
$url = ('myJson.json');
$jsondata = file_get_contents($url);
//convert json object to php associative array
$data = json_decode($jsondata, true);
what do I do here to query the data.json file for a specific array?????
header('Content-Type: application/json; charset=UTF-8');
$json_string = json_encode($????????????, JSON_PRETTY_PRINT);
print $json_string;
Thanks
If I properly understood what you mean, and if your array has always the same tree, this wilp help you access the data :
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
$array = array(
0 => array(
"players" => array(
"name" => "Marcos Alonso",
"position" => "Left-Back",
"nationality" => "Spain",
"marketValue" => "9,000,000 €",
"created" => "2017-04-15 10:04:58"
),
"articles" => array(
"author" => "Stephen Walter",
"title" => "Disruptive stag party revellers thrown off plane at Manchester Airport",
"url" => "http://www.telegraph.co.uk/news/2017/04/15/",
"publishedAt" => "2017-04-15T09:25:10Z"
),
"land" => array(
"state" => "Somewhr",
"found" => "1889",
"area" => "6,812",
"empl" => "1,325",
"ppl" => "16,842"
)
),
1 => array(
"players" => array(
"name" => "Sebastian Vettel",
"position" => "Driver",
"nationality" => "Germany",
"marketValue" => "9,000,000 €",
"created" => "2013-03-15 11:04:52"
),
"articles" => array(
"author" => "Stephen Walter",
"title" => "Disruptive stag party revellers thrown off plane at Manchester Airport",
"url" => "http://www.telegraph.co.uk/news/2017/04/15/",
"publishedAt" => "2017-04-15T09:25:10Z"
),
"land" => array(
"state" => "Somewhr",
"found" => "1889",
"area" => "6,812",
"empl" => "1,325",
"ppl" => "16,842"
)
)
);
/* end of array */
$data1 = json_encode($array); /* just checking - not needed after that */
$data = json_decode($data1, true); /* just checking - not needed after that */
$needle = "articles"; /* should be $needle = $_GET['search']; and checked before use */
//print_r($data); /* just checking */
foreach($data as $value){ /* we access 1st level */
echo '** Needle is: '.$needle.' **<br/>';
foreach($value[$needle] as $sub_key => $sub_data){ /* we access 2nd level */
echo $sub_key.'-->'.$sub_data.'<br/>'; }
}
?>
Once you access the data, you can easily do what you want with it...

fusionCharts data from database in charts

I'm trying to get data from my database into a chart. The charts i'm using are from fusioncharts. If i print the row_cnt's they give me the correct information but in the table it gives me the wrong/no information.
$dbhandle = new mysqli($hostdb, $userdb, $passdb, $namedb);
if ($dbhandle->connect_error) {
exit("There was an error with your connection: ".$dbhandle->connect_error);
}
?>
<html>
<head>
<title>FusionCharts XT - Column 2D Chart - Data from a database</title>
<script src="includes/fusioncharts.js"></script>
<script src="includes/fusioncharts.charts.js"></script>
</head>
<body>
<?php
$result = $dbhandle->query("SELECT * FROM email");
$result2 = $dbhandle->query("SELECT * FROM email WHERE status='1'");
$result3 = $dbhandle->query("SELECT * FROM email WHERE status='0'");
$row_cnt = $result->num_rows;
$row_cnt2 = $result2->num_rows;
$row_cnt3 = $result3->num_rows;
// If the query returns a valid response, prepare the JSON strin
if ($result) {
// The `$arrData` array holds the chart attributes and data
$arrData = array(
"chart" => array
(
"caption" => "Aantal geregistreerde emails",
"paletteColors" => "#0075c2",
"bgColor" => "#ffffff",
"borderAlpha"=> "20",
"canvasBorderAlpha"=> "0",
"usePlotGradientColor"=> "0",
"plotBorderAlpha"=> "10",
"showXAxisLine"=> "1",
"xAxisLineColor" => "#999999",
"showValues" => "0",
"divlineColor" => "#999999",
"divLineIsDashed" => "1",
"showAlternateHGridColor" => "0"
)
);
$arrData["data"] = array();
// Push the data into the array
while($row = mysqli_fetch_array($result)) {
array_push($arrData["data"], array(
"label" => 'active emails',
"value" => $row_cnt,
)
);
}
row_cnt gives me the total amount of emails
row_cnt2 gives me the total active emails
row_cnt3 gives me the total inactive/signedoff emails
in the chart it only gives me the total registered emails (row_cnt) and when i want to try to add the other 2 in the chart its not giving me any information. The bar with the total registered emails is also display twice. Someone know what im doing wrong or how to do this?
I want to display 3 different bars 1 needs to be the total registered emails bar number 2 needs to be the active ones and bar number 3 the inactive ones.
I think, you should simply push the three values $row_cnt, $row_cnt2 and $row_cht3 one after another.
Look at this:
// The `$arrData` array holds the chart attributes and data
// First, add the chart array that describes the chart itself.
$arrData = array(
"chart" => array
(
"caption" => "Aantal geregistreerde emails",
...
...
"showAlternateHGridColor" => "0"
)
);
// Second, we add the values displayed by the bars.
$arrData["data"] = array();
// In this code example, we add the values each by each as they are available in three single variables.
// 1. Total:
array_push($arrData["data"], array(
"label" => 'total emails',
"value" => $row_cnt
));
// 2. Active:
array_push($arrData["data"], array(
"label" => 'active emails',
"value" => $row_cnt2
));
// 3. Active:
array_push($arrData["data"], array(
"label" => 'inactive emails',
"value" => $row_cnt3
));
But maybe you need to loop, as the number of processed values could change and you need to be flexible. In that case I recommend to collect the values in a separate array first and then loop the separate array. Like this:
...
// Second, we add the values displayed by the bars.
$arrData["data"] = array();
// In this code example, we for an array first and are able to loop over it.
$myBarArray = array();
// 1. Total:
$myBarArray[] = array(
"label" => 'total emails',
"value" => $row_cnt
);
// 2. Active:
$myBarArray[] = array(
"label" => 'active emails',
"value" => $row_cnt2
);
// 3. Active:
$myBarArray[] = array(
"label" => 'inactive emails',
"value" => $row_cnt3
);
// Now we can loop this array, or pass it to a further function or whatever:
foreach ($myBarArray as $bar) {
$arrData["data"][] = $bar;
}
Either way, iterating over $result as in your question does not seem to be the right way.
Also please note the syntax with [] instead of array_push(), which sometimes is more readable.
Hope this helps :-)

how to set the php json encode multi dimensional array

Good morning,
I have a very specific example that I am trying to implement. The goal is to get the following JSON end result.
{
merchantId :"123456",
tenderType :"Card",
amount :"0.02",
account :
{
number : "4111",
expiryMonth : "02",
expiryyear : "2016",
cvv : "019",
avsZip : "30014",
avsStreet: "2001 Main"
}
}
I am familiar with json_encode and I have can get this done for the 1st 3 parameters with the following code:
json_encode(
array(
"merchantId" => "123456",
"tenderType" => "Card",
"amount" => "0.02"
)
}
but the 4th parameter (account) is getting me stuck. Can anybody explain to me how to incorporate the 4th parameter that is itself an array.
George
It should just be a nested associative array:
json_encode(
array(
"merchantId" => "123456",
"tenderType" => "Card",
"amount" => "0.02",
"account" => array(
"number" => "4111",
"expiryMonth" => "02",
"expiryyear" => "2016",
"cvv " => "019",
"avsZip" => "30014",
"avsStreet" => "2001 Main"
)
)
)

Looping through an Multidimentinal/Associative Array

Looking for some help with looping through a multidimensional/associative array in PHP. Essentially, I need to loop through and output the certain key values in a table. Not having much luck.
Here is a sample of my array.
$myarray = array(
"body" => array(
"0" => array(
"machine" => array(
"id" => "1",
"name" => "macbookpro",
"description" => "laptop machine",
"state" => "reserved",
"state_since" => "2013-08-28 12:05:00",
"queue_snapshot" => array(
"time" => "2013-08-01 12:00:00",
"jobs" => "450",
"jobs_available" => "90",
"cputime_running" => "00:01:00",
"cputime_eligible" => "00:90:00",
"cputime_block" => " 90:00:00",
)
)
),
"1" => array(
"machine" => array(
"id" => "2",
"name" => "ipad",
"description" => "tablet machine",
"state" => "available",
"state_since" => "2013-08-28 12:05:00",
"queue_snapshot" => array(
"time" => "2013-08-01 12:00:00",
"jobs" => "50",
"jobs_available" => "20",
"cputime_running" => "00:05:00",
"cputime_eligible" => "00:12:00",
"cputime_block" => " 00:10:00",
)
)
)
));
I have some values in this array that will need to be accessed later so I only need to be able to access particular values in order to create this table. Needs to output like this....
Machine Name | Description | State | Jobs | Jobs Available |
macbookpro laptop machine reserved 450 90
ipad tablet machine available 50 20
Untestet on the fly
<?php
if(isset($myarray['body']) && is_array($myarray['body']))
foreach($myarray['body'] as $id=>$arr) {
$name = $arr['name'];
$description = $arr['description'];
$jobs = $arr['queue_snapshot']['jobs'];
$jobs_available = $arr['queue_snapshot']['jobs_available'];
echo "<br>$name $description $jobs $jobs_available";
}
?>

Adding Docusign Template array into REST Header

So I'm back again. My problem is this:
I have an array of Docusign Templates from checkboxes in a Codeigniter view:
<?php
echo form_open('create_envelope');
foreach ($response["envelopeTemplates"] as $envelopeTemplate) { ?>
<li><?php echo form_checkbox('templatearray[]', $envelopeTemplate["templateId"], FALSE), $envelopeTemplate["name"]; ?></li>
<?php } ?>
What I'm trying to do is add the templates to our REST Header request:
$data = array(
"accountId" => $accountId,
"emailSubject" => "Hello World!",
"emailBlurb" => "This comes from PHP",
"templateId" => "ID from template array here",
"templateRoles" => array(
array(
"tabs" => array(
"textTabs" => array (
array (
"tabLabel" => "lic_num",
"value" => "$license_number"
),
array (
"tabLabel" => "ubi_num",
"value" => "$ubi_number"
),
array (
"tabLabel" => "tra_nam",
"value" => "$trade_name"
)
)
),
"email" => "$applicant_email",
"name" => "$applicant_name",
"roleName" => "Applicant"
)
),
"status" => "sent"
);
Is this possible?
EDIT: So I got it to work using loops to get my data in the request, but I'm running into an interesting problem. If I put one or two templates in the envelope, it sends fine. If I put more than two in, it duplicates the templates. Here is my code for the complicated loops:
$compTempArray = array();
$applicant_name = $this->input->post("applicant_name");
$applicant_email = $this->input->post("applicant_email");
$license_number = $this->input->post("license_number");
$ubi_number = $this->input->post("ubi_number");
$trade_name = $this->input->post("trade_name");
foreach($hello as $key => $value) {
if(sizeof($hello) > 1) {
for($i = 1; $i < sizeof($hello); $i++) {
$compTempArray[] = array("serverTemplates" => array(
array(
"sequence" => $i,
"templateId" => $value
)
),
"inlineTemplates" => array(
array(
"sequence" => $i,
"recipients" => array(
"signers" => array(
array(
"tabs" => array(
"textTabs" => array (
array ("tabLabel" => "lic_num", "value" => $license_number),
array ("tabLabel" => "ubi_num", "value" => $ubi_number),
array ("tabLabel" => "tra_nam", "value" => $trade_name)
)
),
"email" => "*********#*****.com",
"name" => $applicant_name,
"recipientId" => "1",
"roleName" => "Applicant"
),
)
)
)
));
}
$data = array("accountId" => $accountId,
"emailSubject" => "Hello World!",
"emailBlurb" => "This comes from PHP",
"compositeTemplates" => $compTempArray,
"status" => "sent");
} else {
$data = array("accountId" => $accountId,
"emailSubject" => "Hello World!",
"emailBlurb" => "This comes from PHP",
"templateId" => "$value",
"templateRoles" => array(
array(
"tabs" => array(
"textTabs" => array (
array ("tabLabel" => "lic_num", "value" => $license_number),
array ("tabLabel" => "ubi_num", "value" => $ubi_number),
array ("tabLabel" => "tra_nam", "value" => $trade_name)
)
),
"email" => "*********#*****.com",
"name" => $applicant_name,
"roleName" => "Applicant"
)
),
"status" => "sent");
}
}
Any idea why it would do this?
NEW EDIT: Update on this weirdness: one to two - one copy of each template, three - it doubles the amount of each template, four - it triples the amount, five - it quadruples the amount.
NEWEST EDIT: So as it turns out, it was the for loop that I was using to try and increment the sequence. I got rid of the loop and hardcoded the sequence to 1. That fixed it.
To apply multiple templates to a single envelope you'll need to use the compositeTemplates structure.
compositeTemplates can get complex very quickly but they do allow for great flexibility and functionality for your envelopes. The API documentation is the best place to read about compositeTemplates but as previously mentioned the April 2012 Templates Webinar is also a good resource. The third example provides a basic use of compositeTemplates in that it shows you how to combine two server templates into one single envelope. You can use that as a base for your JSON.
To apply 2 server templates to a single envelope it uses the following JSON:
{
"emailSubject": "DocuSign Templates Webinar - Example 3",
"emailBlurb": "Example #3 - Composite Templates",
"status": "sent",
"compositeTemplates": [
{
"serverTemplates": [
{
"sequence": "1",
"templateId": "55A80182-2E9F-435D-9B16-FD1E1C0F9D74"
}
],
"inlineTemplates": [
{
"sequence": "1",
"recipients": {
"signers": [
{
"email": "firstrecipient#gmail.com",
"name": "John Doe",
"recipientId": "1",
"roleName": "RoleOne"
}
]
}
}
]
},
{
"serverTemplates": [
{
"sequence": "2",
"templateId": "44D9E888-3D86-4186-8EE9-7071BC87A0DA"
}
],
"inlineTemplates": [
{
"sequence": "2",
"recipients": {
"signers": [
{
"email": "secondrecipient#gmail.com",
"name": "Jane Doe",
"recipientId": "1",
"roleName": "RoleOne"
}
]
}
}
]
}
]
}
Note that the sequence value for each template determines the order of template application to the envelope. So in other words, the sequence value determines the document order, but since the templates might have matching/conflicting info (in terms of template roles for instance) the sequence value might also affect the end result of the envelope.

Categories