php build array/json object structure [duplicate] - php

This question already has answers here:
Push associative array from for-loop in php
(2 answers)
how to append associative arrays into another array inside loop - php
(2 answers)
Insert values into an associative array within a loop
(7 answers)
Closed 3 years ago.
Trying to achieve this structure of jsondata based on an API I am trying to connect to:
{
"VoucherDate": "2019-10-27",
"VoucherText": "string",
"VoucherType": 2,
"Rows": [{
"AccountNumber": 0,
"DebitAmount": 0,
"CreditAmount": 0,
"TransactionText": "string"
},
{
"AccountNumber": 0,
"DebitAmount": 0,
"CreditAmount": 0,
"TransactionText": "string"
}
]
}
The code I have experimented with so far, below, generates this structure. The Rows array doesn't get the same structure as above, where do I do wrong?
{
"VoucherDate": "2019-10-31",
"VoucherText": "string",
"VoucherType": 2,
"Rows": [{
"TransactionText": "test"
}, {
"AccountNumber": 1000
}, {
"DebitAmount": 1
}, {
"CreditAMount": 2
}, {
"TransactionText": "test"
}, {
"AccountNumber": 1000
}, {
"DebitAmount": 1
}, {
"CreditAMount": 2
}]
}
Php code:
$postdata = array();
$postdata["VoucherDate"] = "2019-10-31";
$postdata["VoucherText"] = "string";
$postdata["VoucherType"] = 2;
$postdata["Rows"] = array();
for ($x = 1; $x <= 10; $x++) {
$postdata["Rows"][]["TransactionText"] = "string";
$postdata["Rows"][]["AccountNumber"] = 0;
$postdata["Rows"][]["DebitAmount"] = 0;
$postdata["Rows"][]["CreditAMount"] = ;
}
echo json_encode($postdata);

You need to add all of the elements into one array before adding them to your overall data, something like....
for ($x = 1; $x <= 10; $x++) {
$postdata["Rows"][] = ["TransactionText" => "string",
"AccountNumber" => 0,
"DebitAmount" => 0,
"CreditAMount" = 2];
}

Related

Problem using a for loop in a PHP nested array to it into separate arrays

Am working on a nested array in PHP (From an API) which is 4 levels deep. Am trying to use a for loop to separate/dissect the nested arrays so that they may exist as independent entities so that I may use them in the blade. e.g agency_sales , unit_sales, agents When I dd on the browser, I get agency_sales while unit_sales I only get one array..
They are stored in a variable called rsm
The array collection
"regional_sales": [
{
"id": "75875",
"agency_sales": [
{
"id": "157",
"unit_sales": [
{
"id": "777",
"agents": [
{
"agent_no": "75939",
"policies": [
"IL*********"
]
},
{
"agent_no": "75939",
"policies": [
"IL**********"
]
}
]
},
{
"id": "111",
"agents": [
{
"agent_no": "758",
"policies": [
"IL2*********"
]
},
{
"agent_no": "75939",
"policies": [
"IL20**********"
]
}
]
}
]
}
]
}
]
My For loop
for($a=0; $a < count($rsm); $a++){
$asm = $rsm[$a]['agency_sales'];
//dd($asm);
for($b = 0; $b < count($asm); $b++){
$usm = $asm[$b]['unit_sales'];
dd($usm);
for($c = 0; $c < count($usm); $c++){
$ag = $usm[$c]['agents'];
//dd($ag);
}
}
}
I think you actually want to collect all the pieces at each level separately and then push down to generate the next level arrays. That will ensure you get all the values at each level into their respective array. This should work:
$asm = array();
for($a=0; $a < count($rsm); $a++){
$asm = array_merge($asm, $rsm[$a]['agency_sales']);
}
print_r($asm);
$usm = array();
for($b = 0; $b < count($asm); $b++){
$usm = array_merge($usm, $asm[$b]['unit_sales']);
}
print_r($usm);
$ag = array();
for($c = 0; $c < count($usm); $c++){
$ag = array_merge($ag, $usm[$c]['agents']);
}
print_r($ag);
I've omitted the output as it is quite long but you can see it on the demo on 3v4l.org
You should use foreach to parse through such an array:
foreach ($data['regional_sales'] as $regional_sale) {
// Access $regional_sale['id'] or anything else
foreach ($regional_sale['agency_sales'] as $agency_sale) {
// Access $agency_sale['id'] or anything else
foreach ($agency_sale['unit_sales'] as $unit_sale) {
// Access $unit_sale['id'] or anything else
foreach ($unit_sale['agents'] as $agent) {
// Access $agent['agent_no'] or anything else
}
}
}
}
Demo: https://3v4l.org/q3dAR

Combine two arrays two one and set keys

I have been struggling with this for quite some time. I have two arrays, which I need to combine.
This is my input:
{
"array_one": {
"mrnreference": [
{
"key_0": "18DK00310020B11A84"
},
{
"key_0": "18DK00310020B11B40"
}
]
},
"array_two": {
"shipperreference": [
{
"key_0": "1861575"
},
{
"key_0": "1861549"
}
]
}
}
Now the structure is, that each item in each array follows each other. So, the result should be something like:
{
"result": [
{
"mrn" : "18DK00310020B11A84",
"shipper" : "1861575"
},
{
"mrn" : "18DK00310020B11B40",
"shipper" : "1861549"
}
]
}
However I simply cannot figure out how to do this.
I have tried to merge the two original arrays:
//Input
$array_one = $request->array_one;
$array_two = $request->array_two;
//Merge the two received arrays
$final = array_merge_recursive($array_one, $array_two);
However, this just removes array_one and array_two, but the array is still split up.
How can I combine above array, so it will have below format:
{
"mrn" : "18DK00310020B11B40",
"shipper" : "1861549"
}
You can do this with some custom code:
$array_one = $request->array_one;
$array_two = $request->array_two;
$final = array_map(function ($value, $key) use ($array_two) {
foreach ($value as $k => $v) {
return [
"mrn" => $v,
"shipper" => array_get($array_two, "shipperreference.$key.$k")
];
}
}, array_get($array_one, 'mrnreference'), array_keys(array_get($array_one, 'mrnreference')));
A very quick solution to this would be just to iterate through a for loop.
for($i = 0; $i < count($array_one); $i++){
$final[$i]["mrn"] = $array_one["mrnreference"][$i]; // Mrn key equals array one value
$final[$i]["shipping"] = $array_two["shipperreference"][$i]; // Shipping key equals array two value
}
However, this has a small caveat that it could lead to an error, if $array_one and $array_two are not the same size.
First of all array_map can be used to get the values and then in simple for loop you can combine them. Notice that the size of mrnreference and shipperreference must be the same otherwise it will pop notice
$json = '
{
"array_one": {
"mrnreference": [
{
"key_0": "18DK00310020B11A84"
},
{
"key_0": "18DK00310020B11B40"
}
]
},
"array_two": {
"shipperreference": [
{
"key_0": "1861575"
},
{
"key_0": "1861549"
}
]
}
}
';
$arr = json_decode($json, true);
$ref = array_map(function($e){return $e['key_0'];}, $arr['array_one']['mrnreference']);
$ship = array_map(function($e){return $e['key_0'];}, $arr['array_two']['shipperreference']);
$output = array();
for ($i = 0, $cnt = count($ref); $i < $cnt ; ++$i) {
$output[] = [
'mrn' => $ref[$i],
'shipper' => $ship[$i],
];
}
echo json_encode(['result' => $output]);

Creating custom JSON layout in PHP [duplicate]

This question already has answers here:
Create JSON object using PHP [duplicate]
(5 answers)
Closed 5 years ago.
I'm trying to create JSON in a PHP variable that represents the following JSON structure:
{
"nodes": [
{"id": "example#email.com", "group": 1},
{"id": "Device ID 0eb6823c8e826b6ba6a4fba7459bc77c", "group": 2},
{"id": "Device ID 9057673495b451897d14f4b55836d35e", "group": 2}
],
"links": [
{"source": "example#email.com", "target": "Exact ID 0eb6823c8e826b6ba6a4fba7459bc77c", "value": 1},
{"source": "example#email.com", "target": "Exact ID 9057673495b451897d14f4b55836d35e", "value": 1}
]
}
I'm currently not certain if the best way to do this would be to manually format the JSON layout myself, or if the above structure can be achieved using arrays and json_encode(). It would be good it someone could first confirm the best approach here.
The code I currently have is:
$entityarray['nodes'] = array();
$entityarray['links'] = array();
$entityarray['nodes'][] = '"id": "example#email.com", "group": 1';
$entityarray['nodes'][] = '"id": "Device ID 0eb6823c8e826b6ba6a4fba7459bc77c", "group": 2';
$entityarray['links'][] = '"source": "example#email.com", "target": "Exact ID 0eb6823c8e826b6ba6a4fba7459bc77c", "value": 1';
However when I view the output in JSON format there are some issues:
{
"nodes": ["\"id\": \"example#email.com\", \"group\": 1", "\"id\": \"Device ID 0eb6823c8e826b6ba6a4fba7459bc77c\", \"group\": 2"],
"links": ["\"source\": \"example#email.com\", \"target\": \"Exact ID 0eb6823c8e826b6ba6a4fba7459bc77c\", \"value\": 1"]
}
As you can see the json_encode is causing additional quotation marks with escape \ characters to be added, and each entry isn't stored as an object. Any guidance you can provide would be sincerely appreciated.
It is better using json_encode, note that you should use arrays all the way:
$entityarray['nodes'][] = array( 'id' => 'example#email.com'
, 'group' => 1
);
Try this
$result = array();
$nodes_array = array();
$temp = array();
$temp["id"] = "example#gmamil.com";
$temp["group"] = 1;
$nodes_array[] = $temp;
$temp = array();
$temp["id"] = "Device ID 0eb6823c8e826b6ba6a4fba7459bc77c";
$temp["group"] = 2;
$nodes_array[] = $temp;
$temp = array();
$temp["id"] = "Device ID 9057673495b451897d14f4b55836d35e";
$temp["group"] = 2;
$nodes_array[] = $temp;
$links_array = array();
$temp = array();
$temp["source"] = "example#email.com";
$temp["target"] = "Exact ID 0eb6823c8e826b6ba6a4fba7459bc77c";
$temp["value"] =1;
$links_array[] = $temp;
$temp = array();
$temp["source"] = "example#email.com";
$temp["target"] = "Exact ID 9057673495b451897d14f4b55836d35e";
$temp["value"] =1;
$links_array[] = $temp;
$result["nodes"] = $nodes_array;
$result["links"] = $links_array;
echo json_encode($result);

php - Reach empty JSON array [duplicate]

This question already has answers here:
How to loop through PHP object with dynamic keys [duplicate]
(16 answers)
Closed 6 years ago.
I use Microsoft Face API and I want to show data to final user, but how can I use foreach to atteint faceAttributes->age ?
There is an example of JSON file
[
{
"faceId": "c5c24a82-6845-4031-9d5d-978df9175426",
"faceRectangle": {
"width": 78,
"height": 78,
"left": 394,
"top": 54
},
"faceAttributes": {
"age": 71.0,
"gender": "male",
"smile": 0.88,
"facialHair": {
"mustache": 0.8,
"beard": 0.1,
"sideburns": 0.02
}
},
"glasses": "sunglasses",
"headPose": {
"roll": 2.1,
"yaw": 3,
"pitch": 0
}
}
}
]
I tried this code but not working :
<?php
$json = file_get_contents('file.json');
$data = json_decode($json);
if (count($data->faceAttributes)) {
// Cycle through the array
foreach ($data->faceAttributes as $idx => $faceAttributes) {
// Output a row
echo $faceAttributes->age ;
echo $faceAttributes->gender ;
?>
Thanks !
You don't have to iterate the object using foreach as the 'age' is a property of $data->faceAttributes itself.
Use this instead
if (count($data->faceAttributes)) {
echo $data->faceAttributes->age;
echo $data->faceAttributes->gender;
}
However, $data is an array and which $data you are using is actually $data[0]
So, if there is only one element in data array you can do
$data = $data[0] or $data = json_decode($json)[0]
Or, you can iterate through $data in case of more then one element.

How to sort JSON Array at second level using PHP [duplicate]

This question already has answers here:
How to Sort a Multi-dimensional Array by Value
(16 answers)
Closed 8 years ago.
I like to sort following JSON data by it's value salary using PHP in ascending order.
{
"allresults": [
{
"results": [
{
"Name": "Peter",
"salary": 1000
}
]
},
{
"results": [
{
"Name": "Riya",
"salary": 999
}
]
}
]
}
Required Result:
Riya : 999
Peter : 1000
You can write a custom sort function using uasort. Something like this should work for you:
$data = json_decode($json, true);
uasort($data['allresults'], function($a, $b) {
$aSalary = $a['results'][0]['salary'];
$bSalary = $b['results'][0]['salary'];
return $aSalary - $bSalary;
});
foreach($data['allresults'] as $item) {
printf("%s: %d<br />", $item['results'][0]['Name'], $item['results'][0]['salary']);
}
play with this :
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(your_json($file, TRUE)),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($jsonIterator as $key => $val) {
//your control
}
1st json to php array -> $json_arr = json_decode($json, true);
after that -> you can use array_multisort http://php.net//manual/en/function.array-multisort.php

Categories