How to format json to what I need? - php

ok, Going to get this out of the way right now. I suck at php. I am building an angular app that is going to populate a mobile app with data from the database. I having it pull from the database just fine but I need the json formatted in a special way and I have no idea how to do it.
Using json_encode this is how it is coming from the database:
[
{
"id":"1",
"date":"2014-10-03",
"time":"2014-10-03 10:45:05",
"amount":"5"
},
{
"id":"2",
"date":"2014-10-03",
"time":"2014-10-03 12:21:05",
"amount":"2"
}
]
This is how I need it organized (this is just dummy data im using in on the angular side)
[
{
date: '2014-09-04',
feeding: [
{
id: '1',
time: '1409852728000',
amount: '3'
},
{
id: '2',
time: '1409874328000',
amount: '4'
},
]
},
{
date: '2014-09-05',
feeding: [
{
id: '3',
time: '1409915908000',
amount: '3.5'
},
{
id: '4',
time: '1409957908000',
amount: '5'
},
]
},
]
I needs to be seperated out and grouped by date. How would I go about doing this?

Airtech was just about there. Small update to the function though. The feeding value needs to be an array of objects rather than an object. You then need to push individual objects into that array.
function dateparse($in) {
$in = json_decode($in);
$out = array();
for ($i = 0; $i < sizeof($in); $i++) {
$date = $in[$i]->date;
$isFound = false;
for ($i2 = 0; $i2 < sizeof($out); $i2++) {
if ($date == $out[$i2]["date"]) {
// We've already run into this search value before
// So add the the elements
$isFound = true;
$out[$i2]["feeding"][] = array(
"id" => $in[$i]->id,
"time" => $in[$i]->time,
"amount" => $in[$i]->amount);
break;
}
}
if (!$isFound) {
// No matches yet
// We need to add this one to the array
$feeding = array("id" => $in[$i]->id, "time" => $in[$i]->time, "amount" => $in[$i]->amount);
$out[] = array("date" => $in[$i]->date, "feeding" => array($feeding));
}
}
return json_encode($out);
}

How about the following? I tested it on your json input example and it ran fine.
function parse($in)
{
$in = json_decode($in);
$out = array();
for ($i = 0; $i < sizeof($in); $i++) {
$date = $in[$i]->date;
$isFound = false;
for ($i2 = 0; $i2 < sizeof($out); $i2++) {
if ($date == $out[$i2]["date"]) {
// We've already run into this search value before
// So add the the elements
$isFound = true;
$out[$i2][]["feeding"] = array(
"id" => $in[$i]->id,
"time" => $in[$i]->time,
"amount" => $in[$i]->amount);
break;
}
}
if (!$isFound) {
// No matches yet
// We need to add this one to the array
$out[] = array("date" => $in[$i]->date, "feeding" => array(
"id" => $in[$i]->id,
"time" => $in[$i]->time,
"amount" => $in[$i]->amount));
}
}
return json_encode($out);
}

How about this ? This works fine and works as expected :) :-
function dateparse($var)
{
$counter=0; $var = json_decode($var); $date=array();
foreach($var as $key=>$value){foreach($value as $val1=>$val2)
{if($val1 == "date")
{foreach($value as $val3=>$val4)
{if($val3!="date") //because we don't want date again
{
$date[$val2]["feeding"][$counter][$val3] = $val4; continue;
}}continue;
}
}$counter++;}
return json_encode($date);}

Related

How to get the sum of salaries from a multidimentional array after condition

In this project i have a multidimentional array that keeps some employees names, their position, their speciality and their salary. I need to find the average salary of all the managers and all the employees from the array.
<!DOCTYPE html>
<html>
<head>
<meta sharset="UTF-8"/>
<title>Project3</title>
</head>
<body>
<?php
$employees = array(array("name" => "Nikolaou Nikolaos",
"occupation" => "Employee",
"salary" => 1500,
"specialty" => "Web Programmer"),
array("name" => "Papadopoulou Anna",
"occupation" => "Manager",
"salary" => 2300,
"specialty" => "Human resources management"),
array("name" => "Alexiou Nikoleta",
"occupation" => "Employee",
"salary" => 800,
"specialty" => "Secretary"),
);
//Start of the function that prints the arrays in a specific way.
function printTable($table)
{
foreach ($table as $employee => $list) {
// Print a heading:
echo "<h2 style=\"text-align:left; font-size:26px; font-family:times new roman; color:blue\">Employee #$employee</h2><ul>";
// Print each district data:
foreach ($list as $key => $value) {
echo "<li style=\"text-align:left; font-size:18px; font-family:times new roman; color:black\">$key: $value</li>\n";
}// End of nested FOREACH.
// Close the list:
echo '</ul>';
} // End of main FOREACH.
}// End of the function.
//function that calculates and returns the average salary of employees and managers separately.
function calcMeanAges($table, &$hmean, &$gmean)
{
$cEmployees = 0;
$sumsalary_e = 0;
$cManagers = 0;
$sumsalary_m = 0;
foreach ($table as $occupation =>$list) {
foreach ($list as $salary =>$value) {
if ($occupation == "Employee") {
$cEmployees++;
$sumsalary_e += $salary['salary'];
}
if ($occupation == "Manager") {
$cManagers++;
$sumsalary_m += $salary['salary'];
}
}
}
$hmean = $sumsalary_e / $cEmployees;
$gmean = $sumsalary_m / $cManagers;
}
//call of the function that calculates the average salaries.
calcMeanAges($employees, $h, $g);
echo "$h<br>";
echo "$g";
//Printing the elements of the arrays
echo '<p style="color:red;font-size:28px;font-family:times new roman;"><b>Employees and managers</b></p><br>';
printTable($employees);
?>
</body>
</html>
I need to calculate the average salaries of employees and managers separately. So i thought of putting a condition in the Foreach() to check who is who and then count them and keep the sum of their salary. But it doesn't work properly. I would appreciate some help.
Basically:
To calculate the average sum up all different figures and then divide them through the total amount of figures.
So this part should be right.
Can you please check the datatypes of each from them:
$hmean = $sumsalary_e / $cEmployees;
$gmean = $sumsalary_m / $cManagers;
Every type should be an Integer or Int.
You only need one loop not 2 in this case, then all the occurances you want to check or dd up are members of the inner arrays
function calcMeanAges($table, &$hmean, &$gmean)
{
$cEmployees = 0;
$sumsalary_e = 0;
$cManagers = 0;
$sumsalary_m = 0;
foreach ($table as $item) {
if ($item['occupation'] == "Employee") {
$cEmployees++;
$sumsalary_e += $item['salary'];
}
if ($item['occupation'] == "Manager") {
$cManagers++;
$sumsalary_m += $item['salary'];
}
}
$hmean = $sumsalary_e / $cEmployees;
$gmean = $sumsalary_m / $cManagers;
}
this will proccess any occuption and calculate avarage salary. You can add an IF statment if you only need managers and Employee. You can leave it as be if at a later state other occuptions are added.
$employees = array(
array("name" => "Nikolaou Nikolaos",
"occupation" => "Employee",
"salary" => 1500,
"specialty" => "Web Programmer"),
array("name" => "Papadopoulou Anna",
"occupation" => "Manager",
"salary" => 2300,
"specialty" => "Human resources management"),
array("name" => "Alexiou Nikoleta",
"occupation" => "Employee",
"salary" => 800,
"specialty" => "Secretary"),
);
function averageCount($employees)
{
$count = [];
foreach ($employees as $employee) {
$occupation = $employee['occupation'];
if (!array_key_exists($occupation, $count)) {
$count[$occupation]['occupation'] = $occupation;
$count[$occupation]['salary'] = $employee['salary'];
$count[$occupation]['count'] = 1;
} else {
$count[$occupation]['salary'] += $employee['salary'];
$count[$occupation]['count']++;
}
}
if (count($count) > 0) {
foreach ($count as $occupation => $item) {
$count[$occupation]['average'] = $item['salary'] / $item['count'];
}
}
return $count;
}
var_dump(averageCount($employees));

Translate HTML form request to php array

I have a html form with 3 selector:
a. Room -> 1, 2, 3, 4, 5, 6
b. Adults -> 1, 2, 3, 4, 5, 6
c. Childs -> 0, 1, 2, 3, 4, 5
THe php arrays that i need to get looks like:
Example 1 room with 2 adults
$rooms[] = array(array("paxType" => "Adult"), array("paxType" => "Adult"));
Example 2 rooms ( one room is with two adults and the second room si with 2 adults an
one child
$rooms[] = array(array("paxType" => "Adult"), array("paxType" => "Adult"));
$rooms[] = array(array("paxType" => "Adult"), array("paxType" => "Adult"), array("paxType" =>"Child", "age" => 8));
The variables that i receive from the form are as below:
$City= $_POST['City']; - text
$CheckIN= $_POST['CheckIN']; - text (date)
$CheckOUT= $_POST['CheckOUT']; - text (date)
$Rooms= $_POST['Rooms']; - selector (1,2,3,4,5,6)
$Adults= $_POST['Adults']; - selector (1,2,3,4,5,6)
$Childs= $_POST['Childs']; - selector (0,1,2,3,4,5)
Form is workink fine for text and date input fields.
How can i translate the html form request to get into the a bove look like php arrays.
Thank you for your time.
Entire code is:
// create SOAP client object
$client = new SoapClient("http://www.bookingassist.ro/test/book.wsdl", array('trace' => 1));
try {
function addPaxType($type = null, $amount = 0)
{
$pax = array();
for ($i = 0; $i < amount; $i++)
{
array_push($pax, array('paxType' => $type));
}
return $pax;
}
$RoomsLength = 1;//count($_POST['Rooms']);
$Rooms = array();
//iterate over all rooms
for ($i = 0; $i < $RoomsLength ; $i++)
{
$Rooms[$i] = array();
if ( count($Adults) > 0)
{
//use a function to add adults to room
array_push($Rooms[$i] , addPaxType('Adults', count($Adults)));
}
if (count($Childs) > 0)
{
array_push($Rooms[$i], addPaxType('Childs', count($Childs)));
}
}
$filters = array();
$filters[] = array("filterType" => "hotelStar", "filterValue" => "3", "4", "5");
$filters[] = array("filterType" => "resultLimit", "filterValue" => "7");
// make getAvailableHotel request (start search)
$checkAvailability = $client->getAvailableHotel("gfdgdfgVNhTzA4MVZ3Y2hjTkt3QXNHSXZRYUZOb095Qg==", "RHMK", "2015-03-30", "2015-04-12", "EUR", "RO", "false", $rooms, $filters);
}
catch (SoapFault $exception) {
echo $exception->getMessage();
exit;
}
You can get an array setting in the name input method on the html form post
<br />Room: <input type="text" **name="somearray[]"** required/></br>
After that you can do some like this
$room=$_POST['somearray'];
forgive my bad English!
You need a for lus for this. Based upon the data on this page. I cannot define in which rooms the children and adults are and the age of the children based upon the supplied data. I can however show you an attempt to make such an array.
function addPaxType($type = null, $amount = 0)
{
$pax = array();
for ($i = 0; $i < amount; $i++)
{
array_push($pax, array('paxType' => $type));
}
return $pax;
}
$RoomsLength = count($_POST['Rooms']);
$Rooms = array();
//iterate over all rooms
for ($i = 0; $i < $RoomsLength ; $i++)
{
$Rooms[$i] = array();
if ( count($Adults) > 0)
{
//use a function to add adults to room
array_push($Rooms[$i] , addPaxType('adult', count($Adults)));
}
if (count($Childs) > 0)
{
array_push($Rooms[$i], addPaxType('child', count($Childs)));
}
}
When two rooms are selected and two adults this will output:
$Rooms[0] --> [ [paxType => adult], [paxType => adult] ];
$Rooms[1] --> [ [paxType => adult], [paxType => adult] ];

PHP Getting average grade

I need to get the average number of a grade in a function. Doesn't seem to work completly.. Thanks for your help.
This is what I have so far:
<?php
function povprecje($d,$t){
$v=0;
foreach($t as $x=>$y){
foreach($y as $d=>$grade){
$v = $v+$grade;
$v = $v/count($grade);
return $v;
}
}
}
$t = array(
"Student" => array(
"math" => 3,
"algebra" => 4,
"science" => 4
)
);
echo povprecje("math",$t);
?>
Maybe You wanted to achieve this?
function povprecje($sSubject, $aGrades) {
$iGradesSum = 0;
$iAmount = 0;
foreach($aGrades as $aStudentGrades) {
if(isset($aStudentGrades[$sSubject])) {
$iGradesSum+= $aStudentGrades[$sSubject];
$iAmount++;
}
}
return $iGradesSum / $iAmount;
}
Function call:
echo povprecje("math", $t);

MySQL to nested JSON

This is almost exactly what I want, but that question hasn't been answered and it's been a year. I've managed to get close, I think, but numbers are being printed as keys. In my example it shows up on line 47, but it is repeated for every "course_name" in the actual file.
[
{
"school_name": "Projects",
"terms": [
{
"term_name":"category_name#1",
"departments": [
{
"department_name":"sub_category_name1",
"department_code":"category code text here",
"courses":[
{
"course_name": "project1",
"course_code":"project 1 code text goes here",
"sections":[
{
"section_code":"mike",
"unique_id":"xxx#mail.com"
},
{
"section_code":"dan",
"unique_id":"xxx#gmail.com"
}
]
},
{
"course_name": "project2",
"course_code":"project 2 code text goes here",
"sections":[
{
"section_code":"steve",
"unique_id":"xxx#mail.com"
},
{
"section_code":"chris",
"unique_id":"xxx#gmail.com"
}
]
}
]
},
{
"department_name": "sub_category_name2",
"department_code":"sub category description text goes here..",
"courses": {
-->>> "69": {
"course_name": "project3",
"course_code":"project3 code text goes here ",
"sections":[
{
"section_code":"Alex",
"unique_id":"xxx#gmail.com"
}
]
}
}
}
]
}
]
}
]
Here is the query I am using and an example of data being returned.
SELECT school_name, term_name, department_name, department_code, course_code, course_name, section_code, magento_course_id
FROM schools INNER JOIN term_names ON schools.id=term_names.school_id INNER JOIN departments ON schools.id=departments.school_id INNER JOIN
adoptions ON departments.id=adoptions.department_id
"UCA-2" "SPRING 2013" "ACCOUNTING" "ACCT" "3315" "COST ACCOUNTING" "10258" 10311
What I have is being generated with this code.
$row_array = array();
$terms = array();
$departments = array();
$courses = array();
$h = 0;
$i = 0;
$j = 0;
while ($row = mysqli_fetch_assoc($fetch)) {
$row_array[$row['school_name']]['school_name'] = $row['school_name'];
$akey = array_search($row['term_name'], $terms);
if ($akey === FALSE) {
$m = $h++;
$terms[] = $row['term_name'];
$row_array[$row['school_name']]['terms'][$m]['term_name'] = $row['term_name'];
} else {
$m = $akey;
}
$key = array_search($row['department_code'], $departments);
if ($key === FALSE) {
$k = $i++;
$departments[] = $row['department_code'];
$row_array[$row['school_name']]['terms'][$m]['departments'][$k]['department_name'] = $row['department_name'];
$row_array[$row['school_name']]['terms'][$m]['departments'][$k]['department_code'] = $row['department_code'];
} else {
$k = $key;
}
$skey = array_search($row['course_code'], $courses);
if ($skey === FALSE) {
$l = $j++;
$courses[] = $row['course_code'];
$row_array[$row['school_name']]['terms'][$m]['departments'][$k]['courses'][$l]['course_name'] = $row['course_name'];
$row_array[$row['school_name']]['terms'][$m]['departments'][$k]['courses'][$l]['course_code'] = $row['course_code'];
} else {
$l = $skey;
}
$row_array[$row['school_name']]['terms'][$m]['departments'][$k]['courses'][$l]['sections'][] = array('section_code' => $row['section_code'], 'unique_id' => $row['magento_course_id']);
}
How do I generate this JSON without those numbers showing up?
I think you have some key & encoding problems. Too much key usage, excessive loops in your code. Maybe you should tidy your sql query.
Since you are setting keys for courses, JSON shows it.
Try removing the key after "['courses']" in your last line such as;
Change ['courses'][$l] to ['courses'][]
At the end, encode the array for JSON.
$result = json_encode($result);

Having an issue with array keys, undefined index

I'm working with a couple of arrays, one of which has keys that are the productid, the value being an object that contains a doctrine entity of that product. Similarly, I have a plan with the index being the plan Id. For this for loop, I need to go through and individually set up invoices for each plan-product pair (the quantity will always be the same between them, except in cases where a user is purchasing a plan for an already owned device). Obviously this is somewhat complicated, so I'm not exactly sure how to phrase this question. An error occurs at the commented line, "Notice: Undefined Index"
for ($i = 0; $i < $totalInvoices; $i++) {
if ($i == $planQuantity[key($plans)]) {
next($plans);
}
if ($i == $productQuantity[key($products)]) {
next($products);
}
$data = array(
'planId' => key($plans),
//below here, I'm thinking at key($products) is where the error occurs
'productId' => key($products) != 0 ? key($products) : $plans[key($plans)]->getPricingTier()->getProductId(),
'userId' => $this->userId,
'paymentMethodId' => $paymentMethodId
);
if ($order['hasProduct'] || isset($order['activating'])) {
if (!isset($order['activating'])) {
$planModel->createDevicePlan($data);
$productAmount = $products[key($products)]->getAmount();
} else {
$data['deviceId'] = $order['activating']['inventoryId'];
$planModel->createDevicePlan($data, date('Y-m-d'));
$productAmount = 0;
}
} else {
$productAmount = 0;
}
if ($iteration % 5 == 0 && $order['hasShipping']) {
$invoiceShippingAmount = $billingModel->getShippingAmount($shippingOptionsId);
} else {
$invoiceShippingAmount = 0;
}
$salesData = array(
'paymentMethodsId' => $paymentMethodId,
'planAmount' => $plans[key($plans)]->getAmount(),
'planId' => key($plans),
'productAmount' => $productAmount,
'productId' => key($products),
'shippingAddressesId' => $shippingAddressId,
'shippingAmount' => $invoiceShippingAmount,
'shippingOptionsId' => $shippingOptionsId,
'transactionId' => $transactionId,
'userId' => $this->userId
);
$iteration++;
$billingModel->createInvoice($salesData);
}
Any help would be greatly appreciated.
Based on your comment reply, I think this will help
$plans_on_invoice = 0;
$products_on_invoice = 0;
for ($i = 0; $i < $totalInvoices; $i++) {
next($plans);
if ($plans_on_invoice == 0) {
$plans_on_invoice = $planQuantity[key($plans)];
}
plans_on_invoice--;
next($products);
if ($products_on_invoice == 0) {
$products_on_invoice = $productQuantity[key($products)];
}
products_on_invoice--;

Categories