How to get join table data and pass inside array in php - php

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

Related

PHP merge array by "depth"? [duplicate]

This question already has answers here:
How to array_merge_recursive() an array?
(2 answers)
Closed 3 months ago.
I have an array like this:
[
{
"function_1": {
"element": {
"error": "0",
"msg": "test"
}
}
},
{
"function_1": {
"element_2": {
"error": "0",
"msg": "test"
}
}
},
{
"function_2": {
"element": {
"error": "0",
"msg": "test"
}
}
},
{
"function_2": {
"element_2": {
"error": "0",
"msg": "test"
}
}
}
]
I want output like this:
[
{
"function_1": {
"element": {
"error": "0",
"msg": "test"
},
"element_2": {
"error": "0",
"msg": "test"
}
}
},
{
"function_2": {
"element": {
"error": "0",
"msg": "test"
},
"element_2": {
"error": "0",
"msg": "test"
}
}
}
]
The answers that I found offered to search by name("function_1", "function_2"). But this does not suit me, the function will not always pass an array. I need exactly the "depth" or any other reasonable way.
Thank you!
To achieve your desired result, you could json-decode, recursively merge each individual subarray, then loop over that structure to push each item as a second-level array like this: (Demo)
$array = json_decode($json, true);
$merged = array_merge_recursive(...$array);
$result = [];
foreach ($merged as $key => $data) {
$result[] = [$key => $data];
}
var_export($result);
But I can't imagine getting any benefit from adding unnecessary depth to your result array. I recommend simply json decoding, then calling array_merge_recursive() with the spread operator: (Demo)
var_export(
array_merge_recursive(
...json_decode($json, true)
)
);
Output:
array (
'function_1' =>
array (
'element' =>
array (
'error' => '0',
'msg' => 'test',
),
'element_2' =>
array (
'error' => '0',
'msg' => 'test',
),
),
'function_2' =>
array (
'element' =>
array (
'error' => '0',
'msg' => 'test',
),
'element_2' =>
array (
'error' => '0',
'msg' => 'test',
),
),
)
Your data structure looks weird for the purpose you are trying to achieve I'm bored af tho and created this code for you
function combineElementsPerfunction($functions) {
$result = [];
$uniqueFunctions = [];
foreach ($functions as $function) {
$functionName = array_keys($function)[0];
$uniqueFunctions[] = $functionName;
}
$uniqueFunctions = array_unique($uniqueFunctions);
foreach ($uniqueFunctions as $uniqueFunction) {
$functionObjects = array_filter(
$functions,
function($function) use ($uniqueFunction) {
$functionName = array_keys($function)[0];
return $functionName === $uniqueFunction;
}
);
$elements = [];
foreach ($functionObjects as $functionObject) {
$function = array_shift($functionObject);
$elements = array_merge($elements, $function);
}
$result[] = [
$uniqueFunction => $elements
];
}
return $result;
}
function changeArr($data){
$box = $new = [];
foreach ($data as $v){
$key = array_key_first($v);
$i = count($box);
if(in_array($key, $box)){
$keys = array_flip($box);
$i = $keys[$key];
}else{
$box[] = $key;
}
$new[$i][$key] = isset($new[$i][$key]) ? array_merge($new[$i][$key], $v[$key]) : $v[$key];
}
return $new;
}

codeigniter create response array object

I have the code below, but the result of the json response doesn't match
public function tes_get(){
$kode= $this->M_mymodel->tbl_kode('302'); // row
$res = array();
foreach ($kode as $key=> $value) {
$win = $this->M_mymodel->db_aa('302'); //row_array
$res = $this->M_mymodel->db_bb('302','LOSE'); //row_array
$res['data'][] = array(
'win' => $win['menang'],
'lose' =>$res['kalah']
);
}
$response = $this->set_response($res,200);
}
Below is the result of the response from the code I made above
{
"data": [
{
"win": "2",
"lose": "11"
}
]
}
How to make json response like below?
{
"data": [
{
"win": "2",
}
{
"lose": "11"
}
]
}
You can try :
$res['data'][] = array(
array('win' => $win['menang']),
array('lose' =>$res['kalah'])
);

How do I put multiple values in an array while foreaching through values in PHP

Alright so I'm trying to adjust an array and decode it to json, currently it decodes the array like this;
{"campaignId":"18210f12-502c-4d71-a098-4f595304a8d0","fields.CPLastName":"Voornaam 1","fields.CPFirstname":"Achternaam 1","fields.OROrganisation":"Bedrijf 1"}
{"campaignId":"18210f12-502c-4d71-a098-4f595304a8d0","fields.CPLastName":"Voornaam 2","fields.CPFirstname":"Achternaam 2","fields.OROrganisation":"Bedrijf 2"}
Code:
$request = array();
foreach($address_data as $address) {
foreach($address as $key => $value){
if($key == 'campaignId') {
$request[$key] = $value;
}
if (strpos($key, 'fields') !== false) {
$fields = explode('.', $key);
$request['fields'] = array(
array('fieldId' => $fields[1], 'value' => $value)
);
}
}
echo json_encode($request);
}
What I want to do is, where it says; fields. I want to explode on that and replace fields. with fieldId within a fields array. So something like this;
$request['fields'] = array(array('fieldId' => $key, 'value' => $value));
Now for some reason it will only do the last key, and I want it to loop through all the keys where it says 'fields.'
So the final request should look something like;
{
"campaignId":"18210f12-502c-4d71-a098-4f595304a8d0",
"fields": [
{
"fieldId":"CPLastName",
"value":"Voornaam 1"
},
{
"fieldId": "CPFirstname",
"value": "Achternaam 1"
},
{
"fieldId":"OROrganisation",
"value":"Bedrijf 1"
}
]
}
{
"campaignId":"18210f12-502c-4d71-a098-4f595304a8d0",
"fields": [
{
"fieldId":"CPLastName",
"value":"Voornaam 2"
},
{
"fieldId": "CPFirstname",
"value": "Achternaam 2"
},
{
"fieldId":"OROrganisation",
"value":"Bedrijf 2"
}
]
}
Use a temporary helper variable in cases like this, that you assemble the array data structure for a single item in.
Add that temp array to the result array at the end of the outer loop.
$request = [];
foreach($address_data as $address) {
$temp = [];
foreach($address as $key => $value){
if($key == 'campaignId') {
$temp[$key] = $value;
}
if (strpos($key, 'fields') !== false) { // === 0 would perhaps make more sense here
$fields = explode('.', $key);
$temp['fields'][] = [
'fieldId' => $fields[1],
'value' => $value
];
}
}
$request[] = $temp;
}
echo json_encode($request);

Add another key php array json

Please correct the terminologies that I am using.
I am trying to return a json data like this:
"data": [
{
"id": 1
"name": "test"
},
{
{
"id": 2
"name": "abc"
},
{
"id": 3
"name": "zxc"
}
]
and my code is exactly this one
$data = [];
foreach($prices as $price) {
$data[]["id"] = $price->id;
$data[]["name"] = $price->name;
}
$result["data"] = $data;
the code returns the json like this:
"data": [
{
"id": 1
},
{
"name": "test"
}
{
"id": 2
},
{
"name": "abc"
}
{
"id": 3
},
{
"name": "zxc"
}
]
Sorry for the bad formatting.
Like this
foreach($prices as $price) {
$data[] = [
"id"=> $price->id,
"name" => $price->name
];
}
You are adding the items sequentially, when you need to group them in an array and then add that array as a single unit.
$i = 0;
$data = [];
foreach($prices as $price) {
$data[$i]["id"] = $price->id;
$data[$i]["name"] = $price->name;
$i++;
}
$result["data"] = $data;
The problem is that you keep appending to the array instead of appending to an object and then to the $data array.
Try like this
$data = [];
foreach($prices as $price) {
$topush = [];
$topush["id"] = $price->id;
$topush["name"] = $price->name;
$data[] = $toReturn;
}
$result["data"] = $data;
or, even shorter
$data = [];
foreach($prices as $price) {
$data[] = ['id' => $price->id, 'name' => $price->name];
}
$result["data"] = $data;
You are adding two new Elements to your output, one containing the key/value for id and the other one for name. You have to put both into one element:
$data[]["id"] = $price->id; // Add one element
$data[]["name"] = $price->name; // Add second element
// New
$data[] = ['id' => $price->id, 'name' => $price->name]; // Add both as one Element
Empty [] creates new index every time. You must specify index where you wish to insert:
$data = [];
foreach($prices as $i => $price) {
$data[$i]["id"] = $price->id;
$data[$i]["name"] = $price->name;
}
$result["data"] = $data;
You kept assigning the value to a new key you should assign the data you want bundle in one go.
$data = [];
foreach($prices as $price) {
$data[] = [
"id" => $price->id,
"name" => $price->name;
]
}
$result["data"] = $data;

Trying create an associative array?

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

Categories