I have an array
Array
(
[0] => Array
(
[NT_NOTAFINAL] => 10.00
[M_DESCRICAO] => ARTE
[PE_DESCRICAO] => 1 BIMESTRE
)
[1] => Array
(
[NT_NOTAFINAL] => 10.00
[M_DESCRICAO] => ARTE
[PE_DESCRICAO] => 2 BIMESTRE
)
[2] => Array
(
[NT_NOTAFINAL] => 10.00
[M_DESCRICAO] => ARTE
[PE_DESCRICAO] =>3 BIMESTRE
)
)
Now I'm trying create an associative array to return JSON something like this:
"Materia":[{"descricao":"ARTE", "Notas":["1 BIMESTRE":10.00, "2 BIMESTRE":10.00, "3 BIMESTRE":10.00]}]
I don't know how I could create this associative array to this JSON result from this array that I'm posting.
I'm trying create like this but the result what I need does not return
$notas = '';
$materia = '';
foreach($lista as $value){
if($value["M_DESCRICAO"] != $materia){
$materia = $value["M_DESCRICAO"];
}
$notas = array("Descricao"=>$materia, "Notas"=>array($value["PE_DESCRICAO"]=>$value["NT_NOTAFINAL"]));
}
$result = array("Materia"=>array($notas));
echo json_encode($result);
The result to what I'm trying is
{
"Materia": [
{
"Descricao": "ARTE",
"Notas": {
"3 BIMESTRE": "10.00"
}
}
]
}
How could I create this associative array to return this JSON like I need ?
Edit
$notas = array();
$materia = '';
$materia_array = array();
foreach($lista as $value){
if($materia == ''){
$materia = $value["M_DESCRICAO"];
}
if($value["M_DESCRICAO"] != $materia){
array_push($materia_array, (array("Descricao"=>$materia,"Notas"=>$notas)));
$notas = array();
$materia = $value["M_DESCRICAO"];
}else{
array_push($notas, array($value["PE_DESCRICAO"]=>$value["NT_NOTAFINAL"]));
}
}
$result = array("Materia"=>$materia_array);
echo json_encode($result);
Result
{
"Materia": [
{
"Descricao": "ARTE",
"Notas": [
{
"1 BIMESTRE": "10.00"
},
{
"2 BIMESTRE": "10.00"
},
{
"3 BIMESTRE": "10.00"
}
]
},
{
"Descricao": "C.SOCIAIS",
"Notas": [
{
"2 BIMESTRE": "10.00"
},
{
"3 BIMESTRE": "9.50"
}
]
},
{
"Descricao": "CIÊNCIAS E P. S.",
"Notas": [
{
"2 BIMESTRE": "9.50"
},
{
"3 BIMESTRE": "10.00"
}
]
}
]
}
I've refactored your last edit to remove some code duplication and complexity.
$result = array();
foreach ($lista as $value) {
$materia = $value['M_DESCRICAO'];
if (!isset($result[$materia])) {
$result[$materia] = array(
'Descricao' => $materia,
'Notas' => array()
);
}
$result[$materia]['Notas'][] = array(
$value['PE_DESCRICAO'] => $value['NT_NOTAFINAL']
);
}
$result = array('Materia' => array_values($result));
echo json_encode($result);
In addition to my comment, this would be the code to push all notes to an array as long as the M_DESCRICAO does not change, so the starting array $lista needs to be ordered first. Is this what you were after (code is not tested, office computer :-))?
$notas = $materia = null;
$result = $tmp = array();
$len = count($lista);
for ($i=0;$i<$len;$i++) {
$notas = array();
$materia = $lista[$i]["M_DESCRICAO"];
while (($materia == $lista[$i+1]["M_DESCRICAO"]) && ($i < ($len -1))) {
$notas[$lista[$i]["PE_DESCRICAO"]] = $lista[$i]["NT_NOTAFINAL"];
$i++;
}
// now $notas holds all corresponding entries
$tmp[] = array("Descricao"=>$materia, "Notas" => $notas);
}
$result = array("Materia"=>array($tmp));
echo json_encode($result);
I worked out an untested (there might be some errors, but logically it should work) piece of code, but it might help you:
$notas;
$materia = '';
$materia_array;
foreach($lista as $value){
if($materia == '')
$materia = $value["M_DESCRICAO"];
if($value["M_DESCRICAO"] != $materia){
array_push($materia_array, (array("Descricao"=>$materia,"Notas"=>$notas));
unset($notas); //<--------
$notas = array();//<--------
$materia = $value["M_DESCRICAO"];
}
else
{
array_push($notas, array($value["PE_DESCRICAO"]=>$value["NT_NOTAFINAL"]))
}
}
$result = array("Materia"=>$materia_array);
echo json_encode($result);
This should work for multiple M_DESCRICAO values
Related
I have two tables order and orderDetail. i have multiple delivery address in order detail table based on id of order table
i want to display id from order table and deliveryAddress from order detail table.i am getting below output when i print..
but unable to display delivery_address.please anyone can suggest how i display delivery_address..
{
"responseData": {
"status": 1,
"message": "",
"result": [
{
"Order": {
"id": "677",
"detail_location_instructions": "Near Inox"
},
"OrderDetail": [
{
"order_id": "677",
"delivery_address": "Smart Club Gimnasio - Avenida Álvarez Thomas, Buenos Aires, Autonomous City of Buenos Aires, Argentina"
},
{
"order_id": "677",
"delivery_address": "Lower Fort Street, Dawes Point, New South Wales, Australia"
}
]
},
{
"Order": {
"id": "680"
},
"OrderDetail": []
},
{
"Order": {
"id": "684"
},
"OrderDetail": [
{
"order_id": "684",
"delivery_address": "Four Seasons - Posadas"
}
]
}
]
}
}
below is my code
public function getOrderlist(){
if($this->processRequest){
$err = false;
if(empty($this->requestData['id'])){
$this->responceData['message'] = "Please provide User ID";
$err = true;
}
if(!$err){
$id = trim($this->requestData['id']);
$conditions = array('Order.user_id'=>$id);
$data = $this->Order->find('all',array('conditions'=>$conditions));
if(!empty($data)){
$c = array();
foreach ($data as $key => $value) {
$c[] = array(
'Id' => $value['Order']['id'],
'deliveryAddress' => $value['OrderDetail']['delivery_address']
);
}
}
$this->responceData['result'] = $c;
$this->responceData['status'] = 1;
}
}
}
You have to put the deliveryAddress in array
$c = array();
foreach ($data as $key => $value) {
$myOrders = [
'Id'=>$value['Order']['id'],
'deliveryAddress'=>[]
];
foreach($value['OrderDetail'] as $address){
$myOrders['deliveryAddress'][] = $address['delivery_address'];
}
$c[] = $myOrders;
}
Hope this will help
can you trying below code.
foreach ($data as $key => $value) {
$c[] = array(
'Order' => array(
'id'=>$value['Order']['id'],
'detail_location_instructions' => $value['Order']['detail_location_instructions'],
),
'OrderDetail' => array(
'order_id'=>$value['Order']['id'],
'deliveryAddress' => $value['OrderDetail']['delivery_address'],
),
)
}
There is cases where you dont get the delivery address, in that case, you need to check if it exists first. use the Hash utility for that purpose.
I transformed the data to an array, in order for the class Hash to work.
public function getOrderlist(){
if($this->processRequest){
$err = false;
if(empty($this->requestData['id'])){
$this->responceData['message'] = "Please provide User ID";
$err = true;
}
if(!$err){
$id = trim($this->requestData['id']);
$conditions = array('Order.user_id'=>$id);
$data =(array) $this->Order->find('all',array('conditions'=>$conditions));
if(!empty($data)){
$c = array();
foreach ($data as $key => $value) {
$c[] = array(
'Id' => Hash::get($value, 'Order.id'),
'deliveryAddress' => current(Hash::extract($value, 'OrderDetail.{n}.delivery_address', array()))
);
}
}
$this->responceData['result'] = $c;
$this->responceData['status'] = 1;
}
}
}
Does anyone know of a php function that will take in two objects and return a complete set of differences back as an object?
I'll use json encoded data as an example of what I'm trying to accomplish:
Object A:
{
"Name":"Original",
"Id": 5,
"Data":{
"Value1": 1,
"Value2": [
5, 7, 8, 10
],
"Value3": {
"Exists": true
}
}
}
Object B:
{
"Name":"ThisNameChanged",
"Id": 5,
"Data":{
"Value1": 7,
"Value2": [
5, 8, 9
],
"Value3": {
"Exists": true
}
}
}
Would return:
{
"Name":"ThisNameChanged",
"Data":{
"Value2": {
"1": 8,
"2": 9
}
}
}
If no such function exists (which I guess is likely), how might I write a function to do this? Would anyone be able to provide an example, or the function?
Here is some simple example of function you ask for,
but it is not perfect, just food for thought for you:
function objDiff ($obj1, $obj2) {
$diff=array();
$obj1Arr = (array)$obj1;
$obj2Arr = (array)$obj2;
foreach ($obj1Arr as $key=>$val) {
if (!(isset($obj2Arr[$key]) && $obj2Arr[$key]===$val )) {
if (gettype($val)=='object') {
if (isset($obj2Arr[$key])) {
if (gettype($obj2Arr[$key])=='object') {
$subDiff = objDiff($val,$obj2Arr[$key]);
$diff[$key]=$subDiff;
} else {
$diff[$key]=array($val,$obj2Arr[$key]);
}
} else {
$diff[$key]=array($val,$obj2Arr[$key]);
}
} else {
$diff[$key]=array($val,(isset($obj2Arr[$key]))?$obj2Arr[$key]:null);
}
}
}
return $diff;
}
with this data:
$obj1 = new stdClass();
$obj1->test1 = 1;
$obj1->test2 = 2;
$subObj = new stdClass();
$subObj->test1 = 1;
$subObj->test2 = 2;
$obj1->test3 = $subObj;
$obj2 = new stdClass();
$obj2->test1 = 3;
$obj2->test2 = 4;
$subObj = new stdClass();
$subObj->test1 = 3;
$subObj->test2 = 2;
$obj2->test3 = $subObj;
print_r(objDiff($obj1,$obj2) );
it returns:
Array
(
[test1] => Array
(
[0] => 1
[1] => 3
)
[test2] => Array
(
[0] => 2
[1] => 4
)
[test3] => Array
(
[test1] => Array
(
[0] => 1
[1] => 3
)
)
)
Thanks to Kim Alexander, I was able to write a code that accomplished what I was looking to do.
function objDiff($obj1, $obj2, $diff = null) {
if (is_null($diff))
$diff = new stdClass;
$obj1Arr = (array)$obj1;
$obj2Arr = (array)$obj2;
foreach($obj1Arr as $key => $val) {
if (isset($obj2Arr[$key]))
{
if ($obj2Arr[$key] != $val)
{
if (is_object($obj2Arr[$key]) && is_object($val))
$diff->$key = objDiff($val, $obj2Arr[$key]);
else
$diff->$key = $obj2Arr[$key];
}
}
}
return $diff;
}
I have some case like this:
I have json data:
[{
"1377412272": {
"user_id": "1374050643",
"date": "2013-08-24",
"ip": "::1"
}
},
{
"1377412279": {
"user_id": "1374050643",
"date": "2013-08-25",
"ip": "::1"
}
}
, {
"1377412287": {
"user_id": "1377346094",
"date": "2013-08-25",
"ip": "::1"
}
}, {
"1377413058": {
"user_id": "1374050643",
"date": "2013-08-25",
"ip": "::1"
}
},
{
"1377413069": {
"user_id": "1377346094",
"date": "2013-08-25",
"ip": "::1"
}
}
, {
"1377413074": {
"user_id": "1377346094",
"date": "2013-08-25",
"ip": "::1"
}
},
{
"1377413079": {
"user_id": "1377346094",
"date": "2013-08-25",
"ip": "::1"
}
}
]
An then, I have convert to array PHP
$newArr = array();
foreach ($view['con'] as $key => $value) {
foreach ($value as $k => $v) {
if (isset($newArr[$v['user_id']][$v['date']])) {
$newArr[$v['user_id']][$v['date']]++;
}
else
$newArr[$v['user_id']][$v['date']] = 1;
$newArr[$v['user_id']][$v['date']] = isset($newArr[$v['user_id']][$v['date']]) ? $newArr[$v['user_id']][$v['date']]++ : 1;
}
}
Script above have result in json_encode with structure like this:
Array
(
[A] => Array
(
[2013-08-24] => 1
[2013-08-25] => 2
)
[B] => Array
(
[2013-08-25] => 4
)
)
and finally, I want it to be javascript object
[
["date","A","B"],
[2013-08-24,1,0],
[2013-08-25,2,4]
]
How to make it?...
To get output like this yo should do
$countArr = array();
foreach ($data as $key => $value)
{
foreach ($value as $k => $v)
{
if (isset($countArr[$v['date']][$v['user_id']]))
{
$countArr[$v['date']][$v['user_id']]++;
}
else
{
$countArr[$v['date']][$v['user_id']] = 1;
}
}
}
$newArr = array();
foreach ($countArr as $date => $val)
{
$row = array($date);
$newArr[] = array_merge(array($date), array_values($val));
}
echo "<pre>";
print_r($newArr);
echo json_encode($newArr)
If you print out $newArr it will look like this
Array
(
[0] => Array
(
[0] => 2013-08-24
[1] => 1
)
[1] => Array
(
[0] => 2013-08-25
[1] => 2
[2] => 4
)
)
json_encode will output
[["2013-08-24",1],["2013-08-25",2,4]]
I'm afraid you need to code everything manually.
One (not too simple) solution is this:
<?php
$ori_list = array(
'A'=> array(
'2013-08-24' => 1,
'2013-08-25' => 2,
),
'B'=> array(
'2013-08-24' => 3,
),
);
$modif_list = array();
// prepare the header
$header = array('date');
foreach($ori_list as $key=>$val){
if(!array_key_exists($key, $header)){
$header[] = $key;
}
}
$modif_list[] = $header;
// prepare the date_list
$date_list = array();
foreach($ori_list as $key=>$val){
foreach($val as $date=>$num){
// add the initial row for every date
$registered = false;
foreach($date_list as $date_row){
if($date_row[0] == $date){
$registered = true;
break;
}
}
if(!$registered){
$date_row = array($date);
for($i=0; $i<count($header)-1; $i++){
$date_row[] = 0;
}
$date_list[] = $date_row;
}
// put the right value to the right row
$first_index = 0;
$second_index = 0;
for($i=1; $i<count($header); $i++){
if($header[$i] == $key){
$second_index = $i;
break;
}
}
for($i=0; $i<count($date_list); $i++){
if($date == $date_list[$i][0]){
$first_index = $i;
break;
}
}
$date_list[$first_index][$second_index] = $num;
}
}
$modif_list[] = $date_list;
echo 'The PHP';
echo '<pre>';
var_dump($modif_list);
echo '</pre>';
echo 'The JSON';
echo '<pre>';
echo json_encode($modif_list);
echo '</pre>';
?>
The code will produce something like this (which I hope is what you want):
The PHP
array(2) {
[0]=>
array(3) {
[0]=>
string(4) "date"
[1]=>
string(1) "A"
[2]=>
string(1) "B"
}
[1]=>
array(2) {
[0]=>
array(3) {
[0]=>
string(10) "2013-08-24"
[1]=>
int(1)
[2]=>
int(3)
}
[1]=>
array(3) {
[0]=>
string(10) "2013-08-25"
[1]=>
int(2)
[2]=>
int(0)
}
}
}
The JSON
[["date","A","B"],[["2013-08-24",1,3],["2013-08-25",2,0]]]
PHP
$arr = array("id"=>"1");
json_encode($arr);
Javascript + PHP
var json = jQuery.parseJSON(<?=$arr?>);
var id = json.id;
I think this is what you want
$newArray = array
(
"A" => array
(
"2013-08-24" => 1,
"2013-08-25" => 2
),
"B" => array
(
"2013-08-25" => 4
)
);
$uids=array();
$da = array();
foreach($na as $uid => $value)
{
$uids[] = $uid;
foreach($value as $date => $count)
{
$da[$date][$uid]=$count;
}
}
$ra = array(array("date"));
foreach($uids as $uid)
{
$ra[0][] = $uid;
}
$i = 1;
foreach($da as $date => $value)
{
$ra[$i][] = $date;
foreach($uids as $uid)
{
if(array_key_exists($uid,$value))
{
$ra[$i][] = $value[$uid];
}
else
{
$ra[$i][] = 0;
}
}
$i++;
}
print(json_encode($ra));
Output:
[["date","A","B"],["2013-08-24",1,0],["2013-08-25",2,4]]
In php, lets call it array.php:
// Your final statment of your array.php script must be an echo statment to send the array to jQuery
$ar = array('item1' => 'value1');
$ret_val['a'] = $ar;
echo json_encode($ret_val);
In jQuery (for example, in the callback of $.post, but you can use $.ajax as well)
$.post("/path/to/array.php,
null, // not passing any values to array.php
function(data) {
console.log (data.a.item1); // writes 'value1' to the console
// (note that the 'a' in data.a.item1 in jQuery is the same as the 'a' in $ret_val in PHP)
},
"json");
}
Then you deal with the return value anyway you like, including creating the final object you seek.
I want to dissect an array like this:
[
"ID",
"UUID",
"pushNotifications.sent",
"campaigns.boundDate",
"campaigns.endDate",
"campaigns.pushMessages.sentDate",
"pushNotifications.tapped"
]
To a format like this:
{
"ID" : 1,
"UUID" : 1,
"pushNotifications" :
{
"sent" : 1,
"tapped" : 1
},
"campaigns" :
{
"boundDate" : 1,
"endDate" : 1,
"pushMessages" :
{
"endDate" : 1
}
}
}
It would be great if I could just set a value on an associative array in a keypath-like manner:
//To achieve this:
$dissected['campaigns']['pushMessages']['sentDate'] = 1;
//By something like this:
$keypath = 'campaigns.pushMessages.sentDate';
$dissected{$keypath} = 1;
How to do this in PHP?
You can use :
$array = [
"ID",
"UUID",
"pushNotifications.sent",
"campaigns.boundDate",
"campaigns.endDate",
"campaigns.pushMessages.sentDate",
"pushNotifications.tapped"
];
// Build Data
$data = array();
foreach($array as $v) {
setValue($data, $v, 1);
}
// Get Value
echo getValue($data, "campaigns.pushMessages.sentDate"); // output 1
Function Used
function setValue(array &$data, $path, $value) {
$temp = &$data;
foreach(explode(".", $path) as $key) {
$temp = &$temp[$key];
}
$temp = $value;
}
function getValue($data, $path) {
$temp = $data;
foreach(explode(".", $path) as $ndx) {
$temp = isset($temp[$ndx]) ? $temp[$ndx] : null;
}
return $temp;
}
function keyset(&$arr, $keypath, $value = NULL)
{
$keys = explode('.', $keypath);
$current = &$arr;
while(count($keys))
{
$key = array_shift($keys);
if(!isset($current[$key]) && count($keys))
{
$current[$key] = array();
}
if(count($keys))
{
$current = &$current[$key];
}
}
$current[$key] = $value;
}
function keyget($arr, $keypath)
{
$keys = explode('.', $keypath);
$current = $arr;
foreach($keys as $key)
{
if(!isset($current[$key]))
{
return NULL;
}
$current = $current[$key];
}
return $current;
}
//Testing code:
$r = array();
header('content-type: text/plain; charset-utf8');
keyset($r, 'this.is.path', 39);
echo keyget($r, 'this.is.path');
var_dump($r);
It's a little rough, I can't guarantee it functions 100%.
Edit: At first you'd be tempted to try to use variable variables, but I've tried that in the past and it doesn't work, so you have to use functions to do it. This works with some limited tests. (And I just added a minor edit to remove an unnecessary array assignment.)
In the meanwhile, I came up with (another) solution:
private function setValueForKeyPath(&$array, $value, $keyPath)
{
$keys = explode(".", $keyPath, 2);
$firstKey = $keys[0];
$remainingKeys = (count($keys) == 2) ? $keys[1] : null;
$isLeaf = ($remainingKeys == null);
if ($isLeaf)
$array[$firstKey] = $value;
else
$this->setValueForKeyPath($array[$firstKey], $value, $remainingKeys);
}
Sorry for the "long" namings, I came from the Objective-C world. :)
So calling this on each keyPath, it actually gives me the output:
fields
Array
(
[0] => ID
[1] => UUID
[2] => pushNotifications.sent
[3] => campaigns.boundDate
[4] => campaigns.endDate
[5] => campaigns.pushMessages.endDate
[6] => pushNotifications.tapped
)
dissectedFields
Array
(
[ID] => 1
[UUID] => 1
[pushNotifications] => Array
(
[sent] => 1
[tapped] => 1
)
[campaigns] => Array
(
[boundDate] => 1
[endDate] => 1
[pushMessages] => Array
(
[endDate] => 1
)
)
)
I have this code, which is parcially working... I'm trying to do this:
Array
(
[servicio_id 1] => Array
(
[peticion_id 1] => Array
(...)
[peticion_id 2] => Array
(...)
[peticion_id 3] => Array
(...)
)
[servicio_id 2] => Array
(
[peticion_id 1] => Array
(...)
[peticion_id 2] => Array
(...)
[peticion_id 3] => Array
(...)
)
)
So each [servicio_id] has it's [peticion_id] with its own values... the problem is that my code actually set the same values inside every [peticion_id] array, increasing it's size as long as the loop is running... Any advice on how to clear and start again the [peticion_id] array once the [servicio_id] is finished?
Thank you in advice
while($row = sqlsrv_fetch_array($sqlQuery)) {
if($row['peticion_id'] == 0) {
$ok[] = round($row['valor'], 3);
if($row['media_ok'] == null) {
$medias_ok = array("0", "0", "0", "0");
} else {
$medias_ok = Umbrales::getValues($row['media_ok'], $row['media']);
}
$max_ok[] = $medias_ok[1];
$min_ok[] = $medias_ok[0];
}
if($row['peticion_id'] == 1) {
$ko[] = round($row['valor'], 3);
if($row['media_ok'] == null) {
$medias_ko = array("0", "0", "0", "0");
} else {
$medias_ko = Umbrales::getValues($row['media_ok'], $row['media']);
}
$max_ko[] = $medias_ko[2];
}
if($row['peticion_id'] == 2) {
$rt[] = round($row['valor'], 3);
if($row['media_ok'] == null) {
$medias_rt = array("0", "0", "0", "0");
} else {
$medias_rt = Umbrales::getValues($row['media_ok'], $row['media']);
}
$max_rt[] = $medias_rt[3];
}
$datos[$servicios[$row['servicio_id']]] = array(
"OK" => $ok,
"KO" => $ko,
"RT" => $rt,
"UMBRAL_MIN_OK" => $min_ok,
"UMBRAL_MAX_OK" => $max_ok,
"UMBRAL_MAX_KO" => $max_ko,
"UMBRAL_MAX_RT" => $max_rt
);
}
You need to clear the array on each loop.
After you while it should read:
while($row = sqlsrv_fetch_array($sqlQuery)) {
$ok = array();
$ko = array();
$rt = array();
$min_ok = array();
$max_ok = array();
$max_ko = array();
$max_rt = array();
if($row['peticion_id'] == 0) {