Looping through an Multidimentinal/Associative Array - php

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";
}
?>

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 couple angulargouge to a database and Double arrow message showing up

I'm trying to find a way to get information out of a database and use this information in a graph. Im using a libery (FusionCharts), this has some examples but not with data out of a database. So far i came up this this but im getting an error
Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW)
The example im using is this one Example angulargauge
if ($result) {
$arrData6 = array(
"chart" => array
(
"caption" => "Sended mail",
"lowerlimit" => "0",
"upperlimit" => "100",
"lowerlimitdisplay" =>"0%",
"upperlimitdisplay" => "100%",
"palette" => "1",
"numbersuffix" => "%",
"tickvaluedistance" => "10",
"showvalue" => "0",
"gaugeinnerradius" => "0",
"bgcolor" => "FFFFFF",
"pivotfillcolor" => "333333",
"pivotradius" => "8",
"pivotfillmix" => "333333, 333333",
"pivotfilltype" => "radial",
"pivotfillratio"=> "0,100",
"showtickvalues"=> "1",
"showborder" => "0",
),
"colorRange" => array (
"color" => array
(
"minValue" => "0",
"maxValue" => "50",
"code" => "#e44a00"
),
(
"minValue" => "50",
"maxValue" => "75",
"code" => "#f8bd19"
),
(
"minValue" => "75",
"maxValue" => "100",
"code" => "#6baa01"
)
),
"dials" => array (
"dial" => array (
"value" => "$precentage"
)
)
);
$arrData6["data"] = array();
$jsonEncodedData6 = json_encode($arrData6);
$angularChart = new FusionCharts("AngularGauge", "chart4" , "100%", "200", "chart-5", "json", $jsonEncodedData6);
// Render the chart
$angularChart->render();
}
I can up with this by using the information on the page but since this one got more informatiesets (chart,dials and colors) I haven't been able to figure out how to do it yet.Database how to explaination i used
The $percentage is the result of the total - the not sended mail

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.

making sure a generated array key is unique

I have this array
$array = array(
"one" => "bar",
"two" => "21",
"three" => "22",
"four" => "25",
"five" => array(
"xxxxxxxxxxxxxxxxxx" => array(
"ar1" => "food",
"ar2" => "dr",
"ar3" => "ch",
"ar4" => "ju"
),
"yyyyyyyyyyyyyyyyyyyy" => array(
"ar1" => "food",
"ar2" => "dr",
"ar3" => "ch",
"ar4" => "ju"
)),
"six" => "et",
"seven" => "op",
"eight" => "hjs",
"nine" => array(
"1" => array(
"ar5" => "food",
"ar87" => "dr",
"ar21" => "ch",
"ar443" => "ju"
),
"2" => array(
"73" => "food",
"82" => "dr",
"90" => "ch",
"2123" => "ju"
)),
"ten" => "bar",
"eleven" => "bar",
"twelve" => "bar"
);
and i want to make sure that every new array added must have a unique array key.To do that,i first get all the keys of the others i.e $array['nine'] in my case then run a function until a unique key is found.
To add a new array to $array['nine'] and to get all the keys in nine
$keyedd = array_keys($array['nine']);
$appendThis[''.unique_array_key($keyedd).''] = array(
"73" => "nitrous",
"82" => "oxide",
"90" => "laughing",
"2123" => "gas"
);
$array['nine'] = $array['nine'] + $appendThis;
This is the function
function unique_array_key($the_array){
$r = rand();
if (array_key_exists("$r", $the_array)) {
unique_array_key($the_array);
}
else if(!array_key_exists("$r", $the_array)) {
echo $r;
}
}
Once i run this
[nine] => Array
(
[1] => Array
(
[ar5] => food
[ar87] => dr
[ar21] => ch
[ar443] => ju
)
[2] => Array
(
[73] => food
[82] => dr
[90] => ch
[2123] => ju
)
[] => Array
(
[73] => nitrous
[82] => oxide
[90] => laughing
[2123] => gas
)
)
the newly added array do not have an array key.However,unique_array_key($keyedd); on its own seems to work fine.Why is the function not adding a unique key?.
I would prefer internal PHP functionality for unique key generation:
$appendThis[uniqid()] = array(
"73" => "nitrous",
"82" => "oxide",
"90" => "laughing",
"2123" => "gas"
);
No needs to reinvent wheel. Check documentation for uniqid() function.
Update
If you have web-cluster running your application simultaneously on several hosts with shared data storage, and more than 10000 ID generations in one second just use:
uniqid(php_uname('n'), true)
for ID generation. Your solution with rand() ID generation have only mt_getrandmax() variations. Usually it is 2147483647. With 10000 ID generations in sec you'll get exceed available ID's limit in 2.4 days, and your code will run in infinite loop because every key check in array will have true result and recursively call new ID generation again and again.
Also, your solution make the application performance dependent on data amount. Than more data you'll have, than higher chance of additional loops for ID generation because of duplicates. For example, if you'll have N already stored arrays with unique ID's, there is a chance next ID will be generated for N+1 cycles.
If your project not highload, will be enough uniqid() or uniqid('', true) if you need additional entropy.
Replace echo $r; with return $r;:
function unique_array_key($the_array){
$r = rand();
if (array_key_exists("$r", $the_array)) {
return unique_array_key($the_array);
} else {
return $r;
}
}
}

PHP return array of matching KEY NAMES and there values

I'm having a terrible time trying to pull out some values out of an array. Here is a slimmed down version of the array.
$properties = array( array( PropertyID => 2845,
Address_1 => "1234 Any street",
MEDIA_IMAGE_00 => "23428.jpg",
MEDIA_IMAGE_TEXT_00 => "Front of House",
MEDIA_IMAGE_01 => "29872.jpg",
MEDIA_IMAGE_TEXT_01 => "Master Bedroom",
MEDIA_IMAGE_02 => "29834.jpg"
),
array( PropertyID => 2845,
Address_1 => "555 This street",
MEDIA_IMAGE_00 => "234234.jpg",
MEDIA_IMAGE_TEXT_00 => "Front of House",
MEDIA_IMAGE_01 => "298724.jpg",
MEDIA_IMAGE_TEXT_01 => "Second Bedroom",
MEDIA_IMAGE_02 => "298346.jpg"
),
array( PropertyID => 2845,
Address_1 => "333 Main street",
MEDIA_IMAGE_00 => "2342845.jpg",
MEDIA_IMAGE_TEXT_00 => "Lounge",
MEDIA_IMAGE_01 => "2987246.jpg",
MEDIA_IMAGE_TEXT_01 => "Front of House",
MEDIA_IMAGE_02 => "2983434.jpg"
),
);
There is a massive amount of data in each sub array I've trimmed it down for length...
I'm inserting this data into a MySQL database, however, I'm inserting the images into a separate table [PropertyID, Image, ImageText] because some properties may have more images than others.
So now that the background is out of the way.
How do I pull just the keys of the array that match and there info into another array? So that I would end up with an array from the above that would end up with something similar to:
$property_images = array( array( PropertyID => 2845,
IMAGE => "23428.jpg",
IMAGE_TEXT => "Front of House"),
array( PropertyID => 2845,
IMAGE => "29872.jpg",
IMAGE_TEXT => "Master Bedroom",
array( PropertyID => 2845,
MEDIA_IMAGE_02 => "29834.jpg"
IMAGE_TEXT => "Living Room"
I've tried sscanf to no avail and fiddle around with array_keys but haven't managed to figure out how to target the key names rather than the key values...
Thanks for your help in advance!
Edit:
foreach( $properties as $v ) {
foreach( $v as $k => $m ) {
if( strpos($k, 'MEDIA_IMAGE_TEXT_') !== FALSE ) {
$new_array[] = array('PropertyID' => $v['PropertyID'], 'IMAGE'=>$prev, 'IMAGE_TEXT'=>$m );
}
if( strpos($k, 'MEDIA_IMAGE_') !== FALSE ) {
$prev = $m; //var_dump($prev);
}
}
}

Categories