let say, i have this JSON data i want to print all key by name "id", what should i do?
$json = {"response":[
{
"id": 37,
"slug": "red",
"stock": true,
"name": "Red",
"default": 0,
"sizes": "38"
},
{
"id": 38,
"slug": "red",
"stock": true,
"name": "Red",
"default": 0,
"sizes": "40"
}
]}
i tried this but this one is only giving me first array object sub key(which is id=37) i want all like (id=37, id=38)
$op = $json->{'response'}[0]->{'id'};
If I assume your JSON is really JSON, and therefore a string, you could do this:
$json = '{"response":[
{
"id": 37,
"slug": "red",
"stock": true,
"name": "Red",
"default": 0,
"sizes": "38"
},
{
"id": 38,
"slug": "red",
"stock": true,
"name": "Red",
"default": 0,
"sizes": "40"
}
]}';
$data = json_decode($json);
$ids = array_column($data->response, 'id');
print_r($ids);
This would result in:
Array
(
[0] => 37
[1] => 38
)
See a PHP Fiddle.
You can turn the JSON string into a usable PHP data with json_decode().
The way to get the id's is by using array_column().
You can loop over your response
$array = [];
foreach ($json->{'response'} as $reponseItem){
$array[$reponseItem['id']] = $reponseItem;
}
You need to decode your json string into array 1st and then loop through data.
$json = ' {"response":[
{
"id": 37,
"slug": "red",
"stock": true,
"name": "Red",
"default": 0,
"sizes": "38"
},
{
"id": 38,
"slug": "red",
"stock": true,
"name": "Red",
"default": 0,
"sizes": "40"
}
]}';
$jsonArray =json_decode($json,true); //convert your json string to array.
$newJson = $jsonArray ['response'];
foreach($newJson as $data)
{
echo $data['id'];
}
OR You can directly loop through your $jsonArray['response'].
foreach($jsonArray['response'] as $data)
{
echo $data['id'];
}
$json = '{"response":[
{
"id": 37,
"slug": "red",
"stock": true,
"name": "Red",
"default": 0,
"sizes": "38"
},
{
"id": 38,
"slug": "red",
"stock": true,
"name": "Red",
"default": 0,
"sizes": "40"
}
]}';
$data = json_decode($json); // we decode the JSON
$num = count($data->response); // we count how many response keys we have
$i=0; // define $1=0 to start our iteration
while ($i < $num) { // $i must be < than the counted array keys
$op = $data->response[$i]->id; // we tell the while loop to iterate over the array
print $op."</br>"; // prints out 37 & 38
$i++; // Standard incrementation
}
Related
Im posting a multipart with text and files and trying to pass data to form, but these data are separated, so I want to combine them.
$request->request->all()
$request->files->all()
$form = $this->createForm(ParkingType::class, new Parking());
$form->submit($INeedToPassTheCombinedArray);
if ($form->isValid()) {
return $form->getData();
}
Both arrays have the same structure.
For example:
$request->request->all()
{
"name": "Test",
"taxId": "asd12",
"nationality": "england",
"parkings": [{
"total": 4,
"capacity": 928,
"places": [{
"total": 123,
"name": "test",
"address": "test"
},
{
"total": 123,
"name": "test",
"address": "test"
}
]
}]
}
$request->files->all()
{
"parkings": [{
"generalInfo": "File.pdf",
"places": [{
"logo": "File1.png"
},
{
"logo": "File2.png"
}
]
}]
}
I want to combine then in one single array, getting this:
{
"name": "Test",
"taxId": "asd12",
"nationality": "england",
"parkings": [{
"total": 4,
"capacity": 928,
"generalInfo": "File.pdf",
"places": [{
"total": 123,
"name": "test",
"address": "test",
"logo": "File1.png"
},
{
"total": 123,
"name": "test",
"address": "test",
"logo": "File2.png"
}
]
}]
}
I tried using array_merge, but the result is a single array which contain 2 arrays. It is not adding the data of one array in the respective position of the other array.
I want to know if there is some method for do this automatically and elegant.
Hope this will solve your problem
$data1 = json_decode($data,true);// first post array
$data2 = json_decode($file,true);//second file array
foreach($data1['parkings'] as $key=>&$val){ // Loop though one array
$val2 = $data2['parkings'][$key]; // Get the values from the other array
$val += $val2; // combine 'em
foreach($val['places'] as $k=>&$v){
$val3 = $val2['places'][$k]; // Get the values from the other array
$v += $val3; // combine 'em
}
}
echo json_encode($data1);
{
"name": "Test",
"taxId": "asd12",
"nationality": "england",
"parkings": [
{
"total": 4,
"capacity": 928,
"places": [
{
"total": 123,
"name": "test",
"address": "test",
"logo": "File1.png"
},
{
"total": 123,
"name": "test",
"address": "test",
"logo": "File2.png"
}
],
"generalInfo": "File.pdf"
}
]
}
I have one array with objects, and what I would like to achieve is to group the objects if a similar key already exists. What my JSON output looks like is,
[
{
"id": 37,
"slug": "red",
"stock": true,
"name": "Red",
"default": 0,
"sizes": "38"
},
{
"id": 38,
"slug": "red",
"stock": true,
"name": "Red",
"default": 0,
"sizes": "40"
},
{
"id": 34,
"slug": "red",
"stock": true,
"name": "Red",
"default": 0,
"sizes": "36"
},
{
"id": 26,
"slug": "green",
"stock": true,
"name": "Green",
"default": 0,
"sizes": "48"
}
What I would like to achieve is to group the similar slugs, and have an array of all the sizes in one. So something like this below,
[
{
"slug": "red",
"name": "Red",
"sizes" : [{
"id": 37,
"slug": "red",
"stock": true,
"name": "Red",
"default": 0,
"sizes": "38"
},
{
"id": 38,
"slug": "red",
"stock": true,
"name": "Red",
"default": 0,
"sizes": "40"
},
{
"id": 34,
"slug": "red",
"stock": true,
"name": "Red",
"default": 0,
"sizes": "36"
}]
}, {
"slug": "green",
"name": "Green",
"sizes": [{
"id": 26,
"slug": "green",
"stock": true,
"name": "Green",
"default": 0,
"sizes": "48"
}]
}
]
I'm not so much of a PHP guru, so been trying to figure out all day how to do this searching all over, and hoping someone fluent in PHP can help me out.
You can use one loop to group your result by slug first and then use another to get what you want. Let's try like this way-
<?php
$json = '[{"id":37,"slug":"red","stock":true,"name":"Red","default":0,"sizes":"38"},{"id":38,"slug":"red","stock":true,"name":"Red","default":0,"sizes":"40"},{"id":34,"slug":"red","stock":true,"name":"Red","default":0,"sizes":"36"},{"id":26,"slug":"green","stock":true,"name":"Green","default":0,"sizes":"48"}]';
$array = json_decode($json,1);
$expected = [];
foreach($array as $v) {
$expected[$v['slug']][] = $v;
}
$expected_v2 = [];
foreach($expected as $k1=>$v1) {
array_push($expected_v2,['slug'=>$k1,'name'=>ucfirst($k1),'sizes'=>$v1]);
}
//print_r($expected_v2);
echo json_encode($expected_v2);
?>
Output:
[{"slug":"red","name":"Red","sizes":[{"id":37,"slug":"red","stock":true,"name":"Red","default":0,"sizes":"38"},{"id":38,"slug":"red","stock":true,"name":"Red","default":0,"sizes":"40"},{"id":34,"slug":"red","stock":true,"name":"Red","default":0,"sizes":"36"}]},{"slug":"green","name":"Green","sizes":[{"id":26,"slug":"green","stock":true,"name":"Green","default":0,"sizes":"48"}]}]
DEMO: https://3v4l.org/WfbsX
You can use `array_reduce to achieve this :
$json = '[{"id":37,"slug":"red","stock":true,"name":"Red","default":0,"sizes":"38"},{"id":38,"slug":"red","stock":true,"name":"Red","default":0,"sizes":"40"},{"id":34,"slug":"red","stock":true,"name":"Red","default":0,"sizes":"36"},{"id":26,"slug":"green","stock":true,"name":"Green","default":0,"sizes":"48"}]';
$input = json_decode($json, true);
$output = array_reduce(array_reduce($input, function ($carry, $item) {
$carry[$item['slug']][] = $item;
return $carry;
}, []), function ($carry, $group) {
$carry[] = [
'slug' => $group[0]['slug'],
'name' => $group[0]['name'],
'sizes' => $group
];
return $carry;
}, []);
I have the table "orders" from woocommerce.
I filtered and get sorted the elements by status with GET request.
The results are copied to a JSON file.
So now, I want to find the elements with the same "product_id" and their values and summarize them to display in screen so I can print them.
For example:
"product_id": 45329,
"variation_id": 0,
"quantity": 1
"product_id": 48911,
"variation_id": 0,
"quantity": 1,
"product_id": 45329,
"variation_id": 0,
"quantity": 1
The output that I want to achieve is this:
45329 quantity 2
48911 quantity 1
Thanks!
Decode JSON with json_decode() and make calculations. Next example uses simplified JSON data, which I think matches the format from WooCommerce (I guess this format is from list orders GET request):
<?php
# JSON
$json = '
[
{
"id": 727,
"line_items": [
{
"id": 315,
"name": "Woo Single #1",
"product_id": 93,
"variation_id": 0,
"quantity": 2,
"tax_class": "",
"subtotal": "6.00",
"subtotal_tax": "0.45",
"total": "6.00",
"total_tax": "0.45",
"taxes": [
{
"id": 75,
"total": "0.45",
"subtotal": "0.45"
}
],
"meta_data": [],
"sku": "",
"price": 3
},
{
"id": 316,
"name": "Ship Your Idea – Color: Black, Size: M Test",
"product_id": 22,
"variation_id": 23,
"quantity": 1,
"tax_class": "",
"subtotal": "12.00",
"subtotal_tax": "0.90",
"total": "12.00",
"total_tax": "0.90",
"taxes": [
{
"id": 75,
"total": "0.9",
"subtotal": "0.9"
}
],
"meta_data": [
{
"id": 2095,
"key": "pa_color",
"value": "black"
},
{
"id": 2096,
"key": "size",
"value": "M Test"
}
],
"sku": "Bar3",
"price": 12
}
]
}
]';
$input = json_decode($json, true);
# Sum
$output = array();
foreach ($input as $order) {
foreach ($order["line_items"] as $item) {
$product_id = $item['product_id'];
$quantity = $item['quantity'];
if (!array_key_exists($product_id, $output)) {
$output[$product_id] = 0;
}
$output[$product_id] += $quantity;
}
}
#Output
foreach ($output as $key => $value) {
echo $key.' quantity '.$value.'<br>';
}
?>
Output:
93 quantity 2
22 quantity 1
I have two JSON arrays with some values. I need to merge those values in a format using PHP. Here is the array format and the output format that I needed:
Array 1:
{
"data": {
"1": {
"id": 1,
"name": "red"
},
"25": {
"id": 3,
"name": "green"
}
}
}
Array 2:
{
"data": {
"10": {
"id": 14,
"name": "blue"
},
"22": {
"id": 5,
"name": "white"
}
}
}
Expected Result after merge:
{
"data": {
"1": {
"id": 1,
"name": "red"
},
"25": {
"id": 3,
"name": "green"
}
},
"10": {
"id": 14,
"name": "blue"
},
"22": {
"id": 5,
"name": "white"
}
}
Thank you.
Try this code
<?php
$json1 = '{
"data": {
"1": {
"id": 1,
"name": "red"
},
"25": {
"id": 3,
"name": "green"
}
}
}';
$json2 = '{
"data": {
"10": {
"id": 14,
"name": "blue"
},
"22": {
"id": 5,
"name": "white"
}
}
}';
// Decode json into array
$jArray1 = json_decode($json1, true);
$jArray2 = json_decode($json2, true);
// Merging array
$merge['data'] = $jArray1['data'] + $jArray2['data'];
// Encoding array to json
$mergedJson = json_encode($merge);
print_r( $mergedJson );
?>
$de_json = json_decode('{
"data": {
"1": {
"id": 1,
"name": "red"
},
"25": {
"id": 3,
"name": "green"
}
}}', True);
echo '<pre>';print_r($de_json);
You will get this output
Array
(
[data] => Array
(
[1] => Array
(
[id] => 1
[name] => red
)
[25] => Array
(
[id] => 3
[name] => green
)
)
)
the convert other two json array to php array and
use array_merge() to get the merged array.
i have the following response, how to sort it depending on the distnace
{
"Message": "Done.",
"Status": true,
"InnerData": [
{
"id": 66,
"name": "tito",
"distance": 74,
},
{
"id": 67,
"name": "liver pool",
"distance": 83
},
{
"id": 67,
"name": "Text",
"distance": 72
}
]
}
i tried the usort but i didn't make it.
i also tried this answer here but it seems to be different than the one i need
In pure PHP 7
<?php
$json = '{
"Message": "Done.",
"Status": true,
"InnerData": [
{
"id": 66,
"name": "tito",
"distance": 74
},
{
"id": 67,
"name": "liver pool",
"distance": 83
},
{
"id": 67,
"name": "Text",
"distance": 72
}
]
}';
$array = json_decode($json, true);
usort($array['InnerData'], function($a, $b) {
return $a['distance'] <=> $b['distance'];
});
print_r($array);
As #hdifen suggested, if you're using Laravel it's a breeze to do this.
$json = '{
"Message": "Done.",
"Status": true,
"InnerData": [
{
"id": 66,
"name": "tito",
"distance": 74
},
{
"id": 67,
"name": "liver pool",
"distance": 83
},
{
"id": 67,
"name": "Text",
"distance": 72
}
]
}';
$data = json_decode($json, true);
$data['InnerData'] = collect($data['InnerData'])->sortBy('distance', SORT_REGULAR, true);
$encoded = json_encode($data);
echo $encoded;
Output:
{
"Message":"Done.",
"Status":true,
"InnerData":{
"1":{
"id":67,
"name":"liver pool",
"distance":83
},
"0":{
"id":66,
"name":"tito",
"distance":74
},
"2":{
"id":67,
"name":"Text",
"distance":72
}
}
}
Json is mainly used as a common format for sending data.
In Laravel you can convert a json object to a php array easily by using json_decode().
$phpArray = json_decode($json);
From here you can convert it to a collection to take advantage of laravels collection functions.
$laravelArray = collect($phpArray);
After this take a look at https://laravel.com/docs/5.5/collections to do sort/filter or do whatever you want to the array.