I have 2 arrays ($data_1 & $data_2) which have different value but have a relation, I want to merge those array, completely with key name
$data_1 =
'[
{
"fruit": "apple",
"weight": "15"
},
{
"fruit": "durian",
"weight": "50"
},
{
"fruit": "orange",
"weight": "10"
}
]';
$data_2 =
'[
{
"color": "red",
"thorn": "no"
},
{
"color": "green",
"thorn": "yes"
},
{
"color": "orange",
"thorn": "no"
}
]';
but I want to combine those array, then I have a full data like this:
$full_data =
'[
{
"fruit": "apple",
"weight": "15",
"color": "red",
"thorn": "no"
},
{
"fruit": "durian",
"weight": "50",
"color": "green",
"thorn": "yes"
},
{
"fruit": "orange",
"weight": "10",
"color": "orange",
"thorn": "no"
}
]';
I tried with array_splice()
for ($i=0; $i < count($data_2); $i++) {
array_splice($data_1[$i], 0, 0, $data_2[$i]);
}
but it returns with '0' and '1' not original key name...
'[
{
"fruit": "apple",
"weight": "15",
"0": "red",
"1": "no"
},
{
"fruit": "durian",
"weight": "50",
"0": "green",
"1": "yes"
},
{
"fruit": "orange",
"weight": "10",
"0": "orange",
"1": "no"
}
]';
I want to replace that '0' and '1' into the original key names
Use array_merge to merge two arrays.
$full_data = [];
for ($i=0; $i < count($data_2); $i++) {
$full_data[$i] = array_merge($data_1[$i], $data_2[$i]);
}
Simply, you could do it by
convert two arrays format json into two php arrays using json_decode function.
iterate over one of them and fill $full_data with values of two arrays respectively.
display the array with format json using json_encode function.
// 1.
$data1 = json_decode($data_1,true);
$data2 = json_decode($data_2,true);
// 2.
$full_data = [];
for ($i=0; $i < count($data1); $i++) {
$full_data[$i] = $data1[$i] + $data2[$i];
}
// 3.
echo(json_encode($full_data));
/*
[
{"fruit":"apple","weight":"15","color":"red","thorn":"no"},
{"fruit":"durian","weight":"50","color":"green","thorn":"yes"},
{"fruit":"orange","weight":"10","color":"orange","thorn":"no"}
]
*/
Related
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
}
I'm retrieving data from a database and pushing it to arrays then use json_encode() to output in json format. I have ended up having the data in this format.
[
{
"category_id": "1",
"category_name": "Construction Materials"
},
{
"items": [
{
"id": "1",
"item_name": "Wire Mesh",
"price": "459",
"image_url": null
},
{
"id": "2",
"item_name": "Cement",
"price": "700",
"image_url": null
},
{
"id": "3",
"item_name": "Barbed Wire",
"price": "3000",
"image_url": null
},
{
"id": "4",
"item_name": "Iron sheet",
"price": "200",
"image_url": null
}
]
},
{
"category_id": "2",
"category_name": "Plumbing"
},
Here is what I want to achieve:
[
{
"category_id": "1",
"category_name": "Construction Materials"
"items": [
{
"id": "1",
"item_name": "Wire Mesh",
"price": "459",
"image_url": null
},
{
"id": "2",
"item_name": "Cement",
"price": "40",
"image_url": null
},
{
"id": "3",
"item_name": "Barbed Wire",
"price": "3000",
"image_url": null
},
{
"id": "4",
"item_name": "Iron sheet",
"price": "200",
"image_url": null
}
]
},
{
"category_id": "2",
"category_name": "Plumbing"
},
How can I achive this in php. Is it possible to edit the contents of the main array? how can I add "items" after "category_name"
Regards..
$array = json_decode($yourJson);
$arrayLength = count($array);
$finalArray = [];
for ($i=0; $i < $arrayLength; $i+=2) {
$finalArray[] = $array[$i] + $array[$i + 1];
}
$backToJson = json_encode($finalArray);
Alternative to Mattijs's answer.
function get_first_property($object) {
$properties = array_keys(get_object_vars($object));
return reset($properties);
}
function object_merge($object1, $object2) {
return (object) array_merge((array) $object1, (array) $object2);
}
// loop through each of the array objects
$previous_first_property = null;
foreach ($array as $i => $object) {
$first_property = get_first_property($object);
// merge if the 1st property is "items", and the previous 1st was "category_id"
if ($first_property == "items" && $previous_first_property == "category_id") {
$array[$i - 1] = object_merge($array[$i - 1], $array[$i]);
unset($array[$i]);
}
$previous_first_property = $first_property;
}
I want to reindex my array both key and values in PHP,
example if delete data: "2" , data 3 will be reindex to 2 and values inside of array 3 {sequence : 3 "ssdummy tossssdo 3"} will be change to {sequence : 2 "ssdummy tossssdo 3"}
{
"sequence": 2,
"data": {
"1": {"sequence": "1", "todo": "dummy todo"},
"2": {"sequence": "2", "todo": "dummy todo 2"},
"3": {"sequence": "3", "todo": "ssdummy tossssdo 3"},}
}
First, you can convert your values to a array, as the input is a json. Then parse the array, to remove the required value.
After parsing the array, you can convert it back to json (if it is needed).
The next script remove the value indicated in the $valueToRemove variable.
<?php
$jsonValues = '{
"sequence": 2,
"data": {
"1": {"sequence": "1", "todo": "dummy todo"},
"2": {"sequence": "2", "todo": "dummy todo 2"},
"3": {"sequence": "3", "todo": "ssdummy tossssdo 3"}
}
}';
$valueToRemove = 2;
$arrayValues = json_decode($jsonValues, true);
$oldData = $arrayValues['data'];
$newData = array();
$counter = 0;
foreach ($oldData as $oldIndex => $oldValue) {
if ($valueToRemove != $oldIndex) {
$counter++;
$newData[$counter] = array(
'sequence' => $counter,
'todo' => $oldValue['todo']
);
}
}
$arrayValues['data'] = $newData;
$jsonValues = json_encode($arrayValues);
var_dump($jsonValues);
?>
I have the following output from the script:
{"sequence":2,"data":{"1":{"sequence":1,"todo":"dummy todo"},"2":{"sequence":2,"todo":"ssdummy tossssdo 3"}}}
I have the following performance problem in PHP code. An external API that I cannot edit, returns a JSON array like this one:
[{"name": "Name 1", "code": "Code 1", "attribute1": "Black", "attribute2": "32", "price": "10"},
{"name": "Name 2", "code": "Code 2", "attribute1": "Yellow", "attribute2": "", "price": "15"},
{"name": "Name 1", "code": "Code 3", "attribute1": "Yellow", "attribute2": "32", "price": "20"},....
]
I want to group this by name and reformat it to a JSON array like this:
[{
"name": "Name 1",
"available_attributes": [ "size", "color" ],
"variations": [
{ "attributes": { "size": "32", "color": "Black" }, "price": "10", "code": "Code 1"},
{ "attributes": { "size": "32", "color": "Yellow" }, "price": "20", "code": "Code 3"}
]
}, {
"name": "Name 2",
"available_attributes": [ "color" ],
"variations": [ { "attributes": { "color": "Yellow" }, "price": "15", "code": "Code 2"}]
}]
My solution is ugly and time-consuming since I used a simple brute force to iterate on the response and then again every time on the array to update the one I have already there.
So, I am looking for a solution focused on performance and speed.
Edit. This is my code. The only difference is that in case of both attributes being empty, instead of the variations and available_attributes arrays, it has the price and the sku only.
function cmp( $a, $b ) {
if ( $a['name'] == $b['name'] ) {
return 0;
}
return ( $a['name'] < $b['name'] ) ? - 1 : 1;
}
function format_products_array($products) {
usort( $products, "cmp" );
$formatted_products = array();
$new = true;
$obj = array();
for ( $i = 0; $i < count( $products ); $i++ ) {
if ( $new ) {
$obj = array();
$attr = array();
$obj['available_attributes'] = array();
$obj['variations'] = array();
$obj['name'] = $products[$i]['name'];
if ( $products[$i]['attribute1'] != '' ) {
array_push( $obj['available_attributes'], 'color' );
$attr['color'] = $products[$i]['attribute1'];
}
if ( $products[$i]['attribute2'] != '' ) {
array_push( $obj['available_attributes'], 'size' );
$attr['size'] = $products[$i]['attribute2'];
}
}
if ( $products[ $i ]['name'] == $products[ $i + 1 ]['name']) {
$new = false;
$attr['size'] = $products[$i]['attribute2'];
$attr['color'] = $products[$i]['attribute1'];
if ( empty($obj['available_attributes']) ) {
$obj['price'] = $products[$i]['price'];
} else {
$var = array();
$var['price'] = $products[$i]['price'];
$var['code'] = $products[$i]['code'];
$var['attributes'] = $attr;
array_push($obj['variations'], $var);
}
} else {
$new = true;
if ( empty($obj['available_attributes']) ) {
$obj['price'] = $products[$i]['price'];
}
$attr['size'] = $products[$i]['attribute2'];
$attr['color'] = $products[$i]['attribute1'];
$var['attributes'] = $attr;
array_push($obj['variations'], $var);
array_push($formatted_products, $obj);
}
}
return $formatted_products;
}
A faster solution is when generating the array to store the unique identifies or each object eg to generate:
[
"Name1":{
"name": "Name 1",
"code": "Code 1",
"available_attributes": [ "size", "color" ],
"variations": [
{ "attributes": { "size": "32", "color": "Black" }, "price": "10"},
{ "attributes": { "size": "32", "color": "Yellow" }, "price": "20"}
]
},
"Name2": {
"name": "Name 2",
"code": "Code 2",
"available_attributes": [ "color" ],
"variations": [ { "attributes": { "color": "Yellow" }, "price": "15"}]
}]
OR
[
"Code 1":{
"name": "Name 1",
"code": "Code 1",
"available_attributes": [ "size", "color" ],
"variations": [
{ "attributes": { "size": "32", "color": "Black" }, "price": "10"},
{ "attributes": { "size": "32", "color": "Yellow" }, "price": "20"}
]
},
"Code 2": {
"name": "Name 2",
"code": "Code 2",
"available_attributes": [ "color" ],
"variations": [ { "attributes": { "color": "Yellow" }, "price": "15"}]
}]
Afterwards (optionally)remove any association.
Afterwards you may store them in a memcached/redis then when you need to re-retrieve the same data then just look in redis/memcached first.
So it may be time consuming at first but afterwards it will be ready to do that so they will be only on "unlucky" guy/girl who will do the very same thing.
In case it is extreemely time consuming loops then use a worker to generate theese data ans store them in an document-based storage such as mongodb/couchdb afterwards the site will look on the ready made document.
I have the following MongoDB object:
{
"_id": ObjectId("50954f0d13f88da4a590e5ff"),
"uname": "Eamorr",
"1": {
"table": "1",
"color": "red",
"time": NumberInt(1351963491),
"niceTime": "2012-11-03T17: 24: 51+00: 00"
},
"3": {
"table": "3",
"color": "green",
"time": NumberInt(1351963567),
"niceTime": "2012-11-03T17: 26: 07+00: 00"
},
"4": {
"table": "4",
"color": "orange",
"time": NumberInt(1351963506),
"niceTime": "2012-11-03T17: 25: 06+00: 00"
}
}
How do I sort this object by 'time'?
I want table 3 to be first, table 4 to be second and table 1 to be last in the list.
I'm really stuck... Please help!
Update:
I should add, that my server returns the following JSON object:
[{
"table": "4",
"color": "orange",
"time": 1351965770,
"niceTime": "2012-11-03T18:02:50+00:00"
}, {
"table": "3",
"color": "red",
"time": 1351964379,
"niceTime": "2012-11-03T17:39:39+00:00"
}, {
"table": "1",
"color": "red",
"time": 1351964997,
"niceTime": "2012-11-03T17:49:57+00:00"
}]
Is it easier to sort this?
Many thanks,
$coll->find($range, $co)->sort(array('time' => -1) );
Got it...
Using the second JSON (above), I did:
function my_sort($a, $b){
if ($a['time'] > $b['time']) {
return -1;
} else if ($a['time'] < $b['time']) {
return 1;
} else {
return 0;
}
}
usort($obj,'my_sort');
echo json_encode($obj);