multidimensional array push an objectwise not working properly - php

I have one array which needs to formatted in specific way but it is generating a random key for one of the object. See my code below
$temp = [
[
"UID" => "100",
"UPID" => "001",
"PID" => "test1"
],
[
"UID" => "1001",
"UPID" => "002",
"PID" => "test1"
]
];
$child = [];
foreach ($temp as $key => $value) {
$child[$value['UID']][$key]['UPID'] = $value['UPID'];
$child[$value['UID']][$key]['PID'] = $value['PID'];
}
$oldParentData['childUserProductDetail'] = $child;
echo "<pre>";
$result = json_encode($oldParentData, true);
print_r($result);
my expected output
{
"childUserProductDetail": {
"100": [
{
"UPID": "001",
"PID": "test1"
}
],
"1001": [
{
"UPID": "002",
"PID": "test1"
}
]
}
}
getting output
{
"childUserProductDetail": {
"100": [
{
"UPID": "001",
"PID": "test1"
}
],
"1001": {
"1": { // See 1 as key here, that is unwanted
"UPID": "002",
"PID": "test1"
}
}
}
}
Here i don't have idea second time array is not creating and 1 coming from where.kindly anyone update my code based on my expected answer.

Just small change. Remove the [Key] section that is creating indexes like 0, 1.
So even for UID = 1001 this is first record, but due to loop the key is at 1 which we need to remove.
foreach ($temp as $key => $value) {
$child[$value['UID']][] = ['UPID' => $value['UPID'], 'PID'=> $value['PID']];
}

Related

Sum totals in array based on same keys in subarray in php [duplicate]

This question already has answers here:
PHP - sum values with the same key
(6 answers)
Closed 1 year ago.
I'm trying to add up the total based on the same key.
This my array
[
{
"tipe": "IT",
"kode": "302.1259",
"total": "5"
},
{
"tipe": "ADM",
"kode": "302.1122",
"total": "2"
},
{
"tipe": "IT",
"kode": "302.1000",
"total": "10"
},
{
"tipe": "SUPPORT",
"kode": "302.2389",
"total": "10"
},
]
I want to add up the total based on the same key.
I hope the output is like this
[
{
"tipe": "IT",
"total": "15"
},
{
"tipe": "ADM",
"total": "2"
},
{
"tipe": "SUPPORT",
"total": "10"
},
]
and this is the code I've made, but I still haven't managed to add up the total based on the same key
public function getView()
{
$sum = 0;
$hasil = array();
$satu = $this->my_model->getDB()->result_array();
foreach($satu as $key =>$val){
$cek = $this->my_model->cek_kode($val['kode'])->num_rows();
if ($cek > 0 ) {
$val['total'] = 0;
}
$sum += $val['total'];
$hasil[] = array(
'tipe' => $val['tipe'],
'total' => number_format($sum),
);
}
$response = $this->set_response($hasil,200);
}
I created the function above but it doesn't work
Based on the array you provided, you can add up the totals like this:
$array = [
[
"tipe" => "IT",
"kode" => "302.1259",
"total" => "5"
],
[
"tipe" => "ADM",
"kode" => "302.1122",
"total" => "2"
],
[
"tipe" => "IT",
"kode" => "302.1000",
"total" => "10"
],
[
"tipe" => "SUPPORT",
"kode" => "302.2389",
"total" => "10"
]
];
$totals = [];
foreach ($array as $item) {
if (!array_key_exists($item['tipe'], $totals)) {
$totals[$item['tipe']] = (int)$item['total'];
continue;
}
$totals[$item['tipe']] += (int)$item['total'];
}

Php json_encode array and object array

I need to create a json with this format:
{
"reservs": [
{
"ResId": "58",
"time": "2020-05-15 19:41:50",
"boxEntering": null,
"boxClosing": null,
"active": "1",
"UserId": "29",
"BoxId": "4",
"boxPlace": null,
"box": {
"id": "4",
"Nom": "Hortillonages",
"Lat": "49.8953",
"Lng": "2.31034",
"place": "0",
"placeMax": "9"
}
}
]
}
in entries, a $header who check the user token(not use for my problem)
$table the table returned from PDO::FETCHASSOC from sql SELECT request
My php code:
function generateJson($table, headerChecker $header){
$final = array();
foreach ($table as $item) {
$box = array(
"id" => $item["id"],
"Nom" => $item["Nom"],
"Lat" => $item["Lat"],
"Lng" => $item["Lng"],
"place" => $item["place"],
"placeMax" => $item["placeMax"]
);
$reserv = array(
"ResId" => $item["ResId"],
"time" => $item["time"],
"boxEntering" => $item["boxEntering"],
"boxClosing" => $item["boxClosing"],
"active" => $item["active"],
"UserId" => $item["UserId"],
"BoxId" => $item["BoxId"],
"boxPlace" => $item["boxPlace"],
);
$reserv["box"] = $box;
array_merge($final,$reserv);
}
$arr = array("reservs" => $table);
$header->tokenJson($arr);
echo json_encode($arr);
}
I have this result
{"reservs": [
{
"ResId": "58",
"time": "2020-05-15 19:41:50",
"boxEntering": null,
"boxClosing": null,
"active": "1",
"UserId": "29",
"BoxId": "4",
"boxPlace": null,
"id": "4",
"Nom": "Hortillonages",
"Lat": "49.8953",
"Lng": "2.31034",
"place": "0",
"placeMax": "9",
"QRID": "",
"boxToken": ""
}]
}
I think the Json format eror is in the array_merge function.
What add array function can I use to not remove the Box object
Your problem is that you are not assigning the return of array_merge and using the wrong variable $table. Just dynamically append to $final:
foreach ($table as $item) {
// this all appears good
//
$reserv["box"] = $box;
$final[] = $reserv; // append to $final
}
$arr = array("reservs" => $final); // use $final
$header->tokenJson($arr);
echo json_encode($arr);
Merge the new $reserv into $final and assign it to $final, then use $final.
Try this one
function generateJson($table, headerChecker $header){
$final = array();
foreach ($table as $item) {
$box = array(
"id" => $item["id"],
"Nom" => $item["Nom"],
"Lat" => $item["Lat"],
"Lng" => $item["Lng"],
"place" => $item["place"],
"placeMax" => $item["placeMax"]
);
$reserv = array(
"ResId" => $item["ResId"],
"time" => $item["time"],
"boxEntering" => $item["boxEntering"],
"boxClosing" => $item["boxClosing"],
"active" => $item["active"],
"UserId" => $item["UserId"],
"BoxId" => $item["BoxId"],
"boxPlace" => $item["boxPlace"],
);
$reserv["box"] = $box;
$final[] = $reserv;
}
$arr = array("reservs" => $final);
$header->tokenJson($arr);
echo json_encode($arr);
}

merge array keys and add the values-PHP

I want to merge two same keys in an array and get the sum of the values.
I want the same structure as it is now.Because this data needs to be converted to JSON.
This is what i get now.
{
"data": [{
"count_of_invites": 5,
"user": "Rajesh",
"id": "53"
},
{
"count_of_invites": 9,
"user": "Student",
"id": "45"
},
{
"count_of_invites": 4,
"user": "Student",
"id": "45"
}
]
}
As you can see the id 45 are repeated.As i want the result as,
Expected output
{
"data": [{
"count_of_invites": 5,
"user": "Rajesh",
"id": "53"
},
{
"count_of_invites": 13,
"user": "Student",
"id": "45"
}
]
}
As you can see the duplicate entry should be removed as well as the count_of_invites of duplicate entry should be added.
<?php
$data = [
[
'id' => 2,
'name' => 'Paul',
'count' => 4
],
[
'id' => 3,
'name' => 'Peter',
'count' => 5
],
[
'id' => 3,
'name' => 'Peter',
'count' => 7
]
];
foreach($data as $array)
$counts[$array['id']][] = $array['count'];
$counts = array_map('array_sum', $counts);
foreach($data as $k => $array)
$data[$k]['count'] = $counts[$array['id']];
$data = array_unique($data, SORT_REGULAR);
print json_encode($data, JSON_PRETTY_PRINT);
Output:
[
{
"id": 2,
"name": "Paul",
"count": 4
},
{
"id": 3,
"name": "Peter",
"count": 12
}
]
You can achieve it this way:
$ids = array();
$output = array();
foreach ($input as $value) {
if (!isset($ids[$value["id"]])) {
$ids[$value["id"]]=$count($output);
$output[]=$value;
} else {
$output[$ids[$value["id"]]]["count_of_invites"] = $value["count_of_invites"];
$output[$ids[$value["id"]]]["user"] = $value["user"];
}
}
The count method was declared as variable and i've added with addition assignment operator.
Thank You for helping.
$ids = array();
$output = array();
foreach ($response as $value) {
if (!isset($ids[$value["id"]])) {
$ids[$value["id"]] = count($output);
$output[] = $value;
}
else {
$output[$ids[$value["id"]]]["count_of_invites"] += $value["count_of_invites"];
$output[$ids[$value["id"]]]["user"] = $value["user"];
}
}

Php - creating json object

I am trying to create a json object from the data that I get from Ninja Forms that would look like this:
{
"title": "Contact Me",
"fields": [
{
"label": "Name",
"type": "textbox",
"required": "1"
},
{
"label": "Email",
"type": "email",
"required": "1"
}
]
}
I am trying to do so, like this:
$settings = ['label', 'type', 'required'];
$formTitle = Ninja_Forms()->form( 1 )->get()->get_setting('title');
$formFields = Ninja_Forms()->form(1)->get_fields();
$data = ['title' => $formTitle];
foreach ($formFields as $formField) {
$key = $formField->get_setting('key');
foreach ($settings as $setting) {
$data['fields'][$key][][$setting] = $formField->get_setting($setting);
}
}
return $data;
But, the result of that looks like this:
{
"title": "Contact Me",
"fields": {
"name": [
{ "label": "Name" },
{ "type": "textbox" },
{ "required": "1"}
],
"email": [
{ "label": "Email" },
{ "type": "email" },
{ "required": "1" }
],
How can I do this, so that the result looks like the one I have shown above?
I have also tried like this:
foreach ($settings as $setting) {
$data['fields'][] = $formField->get_setting($setting);
}
But, that gave me this kind of result:
{
"title": "Contact Me",
"fields": [
"Name",
"textbox",
"1",
"Email",
"email",
"1",
"Message",
"textarea",
"1",
"Submit",
"submit",
null
]
}
This gave me the wanted result:
foreach ($formFields as $formField) {
$key = $formField->get_setting('key');
foreach ($settings as $setting) {
$object[$setting] = $formField->get_setting($setting);
}
$data['fields'][] = $object;
}
return $data;
One way to look at this is to count the dimensions of the data. In your desired format, the deepest item is:
{ "fields": [ { "label": "Name"
So you have object -> array -> object.
If we indent each array in your code, we have:
$data // outermost array
['fields']
[$key]
[] // innermost array
[$setting] = $value; // key in innermost array
Or if we were to declare it with just one value:
$data = array(
'field' => array(
$key => array(
0 => array(
$setting => $value
)
)
)
);
So you have 4 levels of array, instead of 3.
Comparing to the JSON, taking an array with numeric keys as "array" and one with non-numeric keys as "object", the pattern is object -> object -> array -> object.
So it's the [$key] we need to eliminate, because it's creating an extra object dimension.
But we don't want to increment the key at [] for each item either, so we need to either make our value in advance...
foreach ($settings as $setting) {
$object[$setting] = $formField->get_setting($setting);
}
$data['fields'][] = $object;
...or choose our key in advance:
$i++;
foreach ($settings as $setting) {
$data['fields'][$i] = $formField->get_setting($setting);
}

Finding a value in php multidimensional array and adding data to that array

I have a multidimensional JSON array that I need to add values to. The JSON array is external and I cannot change its format.
I've tried doing 3 foreach loops, but then I get myself lost in how to add data to the array. I keep catching myself stuck in a loop.
Here's the JSON:
{
"positions": [{
"report_at": "2017-03-13 20:04:10",
"elev": "0",
"dir": "0",
"id": "1"
}, {
"report_at": "2017-03-07 00:28:14",
"elev": "1240",
"dir": "89",
"id": "2"
}]
}
I have unique data I need to add to id 1, and another set of unique data I need to add to id 2.
Here's what I've tried:
$data = json_decode( $result, true );
foreach ( $data as $d ) {
foreach ( $d as $key => $data ) {
if ( $data['id'] == '1' ) {
$data[] = array(
"online_status" => "1",
"name" => "Test User",
);
} elseif ( $data['id'] == '2' ) {
$data[] = array(
"online_status" => "0",
"name" => "Another User",
);
}
}
}
$json = json_encode( $data );
echo $json;
I think once I can get this figured out, then I can pull data from MySQL, build small arrays based off that data, then add those to these sub-arrays where the ID matches the SQL ID. Any help is appreciated.
JSON seems to be just object with "positions" field which is array, you need to modify.
$data = json_decode($json, TRUE);
foreach ($data['positions'] as &$userInfo) {
if ($userInfo['id'] == 1) {
$userInfo['online_status'] = 'offline';
$userInfo['name'] = 'Test user';
}
}
echo json_encode($data);
Notice "&" sign in foreach, which means, that modification made within foreach, will be stored to original array.
Also you should be aware of key=>value naming in foreach. Your second foreach creates variable named $data, which means, that you are loosing pointer to original array!
Use the following approach:
$data = json_decode($result, true);
foreach ($data['positions'] as &$item) {
if ($item['id'] == "1") {
$item = array_merge($item, ["online_status" => "1", "name" => "Test User"]);
} else if ($item['id'] == "2") {
$item = array_merge($item, ["online_status" => "0", "name" => "Another User"]);
}
}
$json = json_encode($data, JSON_PRETTY_PRINT);
echo $json;
The output:
{
"positions": [
{
"report_at": "2017-03-13 20:04:10",
"elev": "0",
"dir": "0",
"id": "1",
"online_status": "1",
"name": "Test User"
},
{
"report_at": "2017-03-07 00:28:14",
"elev": "1240",
"dir": "89",
"id": "2",
"online_status": "0",
"name": "Another User"
}
]
}

Categories