John Davidson

php - How to add data to the array correctly

0 comments
Message:


Help me how to add data to the array correctly.Below I give an example of what I want to get in the end after printing the array


$arr = [];

$data = [
"offer_id" => (string)777380,
"price" => (string)5633
];

array_push($arr, $data);


print_r(json_encode($arr));

I want to get this


    {
"prices": [
{
"offer_id": "777380",
"price": "5633"
},
{
"offer_id": "777380",
"price": "5633"
}
]
}


My Answer:
To achieve the desired output, you can modify your code as follows:

php
$arr = [];

$data = [
"offer_id" => "777380",
"price" => "5633"
];

array_push($arr, $data);
array_push($arr, $data); // Add the same data again to the array

$output = [
"prices" => $arr
];

print_r(json_encode($output));


This code will add the data to the array twice and then create the desired output structure with the key "prices" containing an array of the data. When you print the encoded JSON, you should see the output you specified.

Rate this post

3 of 5 based on 9675 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us