Add another item to array associative in php - php

im having some issues adding a new item to an associative array,
This is how i'm creating my structure:
$cpdata[$count] = array(
'value' => $value->value,
'images' => array(
'color' => $value->color,
'image' => $value->image,
),
);
and this is how it looks like when i output like a json:
{
"value": "BOX",
"images": {
"color": "white",
"image": "white.png"
}
}
But i would like to add more items to images somthing like this:
{
"value": "BOX",
"images": [
{
"color": "white",
"image": "white.png"
},
{
"color": "black",
"image": "black.png"
},
{
"color": "gray",
"image": "gray.png"
}
]
}
I've tried with array_push and array_merge but i cant get it
i've tried array_push($cpdata['images'][$count]['images'], 'color'=>'red', image' => 'red.png')
Could you please help me?
Regards
Mario

In context of PHP, what you have there is a JSON variable. If that is coming to you as a string you'll have to decode it first using json_decode($string);
Then you can set up an object, populate it with the image variables and write it back to the $json object as an array, like:
<?php
// example code
$json = <<<EOT
{
"value": "BOX",
"images": {
"color": "white",
"image": "white.png"
}
}
EOT;
$json = json_decode($json);
$i = new stdClass;
$i->color = $json->images->color;
$i->image = $json->images->image;
$json->images = array($i);
After that you can push to it like
$newimage = new stdClass;
$newimage->color = "foo";
$newimage->image = "bar";
$json->images[] = $newimage;
output
print_r($json);
stdClass Object
(
[value] => BOX
[images] => Array
(
[0] => stdClass Object
(
[color] => white
[image] => white.png
)
[1] => stdClass Object
(
[color] => foo
[image] => bar
)
)
)
example https://www.tehplayground.com/oBS1SN1ze1DsVmIn

Before converting into json
$cpdata[$count] = array(
'value' => $value->value,
'images' => array(
'color' => $value->color,
'image' => $value->image,
),
);
// Cpdata array has $count which has `images` as an array and we want to push another element(array) into images array
array_push($cpdata[$count]['images'], ['color'=>'red', 'image' => 'red.png']);

Related

Difficulty to understand PHP POST to REST API - mixed array and objects

I'm trying to POST data to a REST API.
On Postman I can POST with success, the JSON body is:
{
"version": 0,
"roles": {
"customer": {
}
},
"person": {
"firstName": "Inge",
"lastName": "Musterfrau"
},
"emailAddresses" :{
"private" : [
"email#domain.com"
]
},
"addresses": {
"billing": [
{
"supplement": null,
"street": "aaa",
"zip": "12345",
"city": "Berlin",
"countryCode": "DE"
}
]
}
}
My problem is on addresses billing. I don't know how to create the object/array correctly so the API accept it.
I'm build the parameters on PHO like bellow:
$billingAddr = array(
"supplement" => $billingAddress["streetDetails"],
"street" => $billingAddress["street"],
"zip" => $billingAddress["zipCode"],
"city" => $billingAddress["city"],
"countryCode" => $billingAddress["country"],
);
$params = [
"version" => 0,
"roles" => $roles,
"person" => $person,
"emailAddresses" => $emailAddresses,
"addresses" => [
"billing" => $billingAddr
]
];
I get an error: "missing_entity - addresses - validation_failure".
I believe my issue is creating the mixed Object addresses, array billing.
So, going strictly by the PHP example, doing a json_encode'd output of that shows that the structure is not quite the same at the addresses.
Note that I do not have the data for most of the rest of the json info from the PHP example, so the output examples below are strictly focused on the addresses section.
Before JSON change:
echo json_encode($params, JSON_PRETTY_PRINT);
{
"version": 0,
"roles": null,
"person": null,
"emailAddresses": null,
"addresses": {
"billing": {
"supplement": null,
"street": null,
"zip": null,
"city": null,
"countryCode": null
}
}
}
... in that, note that the billing does not have the [] characters like what is sent using postman.
No worries though, it's an easy fix. The addresses part should be changed to get an array of billing addresses, like so:
"addresses" => [
"billing" => [$billingAddr]
]
Then running a recheck with that change applied shows:
After JSON change:
echo json_encode($params, JSON_PRETTY_PRINT);
{
"version": 0,
"roles": null,
"person": null,
"emailAddresses": null,
"addresses": {
"billing": [
{
"supplement": null,
"street": null,
"zip": null,
"city": null,
"countryCode": null
}
]
}
}
That should help to achieve the expected format.
Here's the fiddle example in case you might need another PHP version to check. The fiddle default is 8.0.1
Object properties and associative arrays are easy to access/declare directly; however, when you need to push data into indexed subarrays, you can to use [] syntax or array_push().
If you want to build a bit more maintainability in this code, you can build the variable-length subarrays as individual variables and then feed them into the master array just before json_encoding.
$version = 0;
$roles = ['customer' => []];
$person = [
'firstName' => 'Inge',
'lastName' => 'Musterfrau'
];
$emailAddresses = [
'private' => [
'email#domain.com',
]
];
$billingAddresses[] = [
'supplement' => $billingAddress["streetDetails"],
'street' => $billingAddress["street"],
'zip' => $billingAddress["zipCode"],
'city' => $billingAddress["city"],
'countryCode' => $billingAddress["country"]
];
// use $billingAddresses[] again to push another subarray into $billing
$data = [
'version' => $version,
'roles' => $roles,
'person' => $person,
'emailAddresses' => $emailAddresses,
'addresses' => [
'billing' => $billingAddresses
]
]
This will create your array/json :
$arr['version'] = "0";
$arr['roles']['customer'] = [];
$arr['person']['firstName'] = "Inge";
$arr['person']['lastName'] = "Musterfrau";
$arr['emailAddresses']['private'][] = "email#domain.com";
$arr['addresses']['billing'][0]['supplement'] = "";
$arr['addresses']['billing'][0]['street'] = "aaa";
$arr['addresses']['billing'][0]['zip'] = "12345";
$arr['addresses']['billing'][0]['city'] = "Berlin";
$arr['addresses']['billing'][0]['countryCode'] = "DE";
$newJson = json_encode($arr);
Afterwards you json_encode it and voila the perfect json and very simple!
The best and easiest way to look at a json (to my opinion at least:) is as an array! (no shame in using the browser and echo "<pre>" here!) - We'll build an identical array and json it up back!
Once we see the json as an array we build the same in a very simple way here is the whole code example with step by step:
<?php
/*Our original json */
$json = '{
"version": 0,
"roles": {
"customer": {
}
},
"person": {
"firstName": "Inge",
"lastName": "Musterfrau"
},
"emailAddresses" :{
"private" : [
"email#domain.com"
]
},
"addresses": {
"billing": [
{
"supplement": null,
"street": "aaa",
"zip": "12345",
"city": "Berlin",
"countryCode": "DE"
}
]
}
}';
$array = json_decode($json,true);
echo '<pre>';
/* original array */
echo "original array: ";
print_r($array);
echo '<pre>';
/* now lets create the same array with less fuss?! */
$arr['version'] = "0";
$arr['roles']['customer'] = [];
$arr['person']['firstName'] = "Inge";
$arr['person']['lastName'] = "Musterfrau";
$arr['emailAddresses']['private'][] = "email#domain.com";
$arr['addresses']['billing'][0]['supplement'] = "";
$arr['addresses']['billing'][0]['street'] = "aaa";
$arr['addresses']['billing'][0]['zip'] = "12345";
$arr['addresses']['billing'][0]['city'] = "Berlin";
$arr['addresses']['billing'][0]['countryCode'] = "DE";
/* the new array: */
echo "our newly created array: ";
echo '<pre>';
print_r($arr);
echo '<pre>';
/* back to json */
echo "new Json: ";
echo '<pre>';
$newJson = json_encode($arr);
print_r($newJson);
This will return:
original array: Array
(
[version] => 0
[roles] => Array
(
[customer] => Array
(
)
)
[person] => Array
(
[firstName] => Inge
[lastName] => Musterfrau
)
[emailAddresses] => Array
(
[private] => Array
(
[0] => email#domain.com
)
)
[addresses] => Array
(
[billing] => Array
(
[0] => Array
(
[supplement] =>
[street] => aaa
[zip] => 12345
[city] => Berlin
[countryCode] => DE
)
)
)
)
our newly created array:
Array
(
[version] => 0
[roles] => Array
(
[customer] => Array
(
)
)
[person] => Array
(
[firstName] => Inge
[lastName] => Musterfrau
)
[emailAddresses] => Array
(
[private] => Array
(
[0] => email#domain.com
)
)
[addresses] => Array
(
[billing] => Array
(
[0] => Array
(
[supplement] =>
[street] => aaa
[zip] => 12345
[city] => Berlin
[countryCode] => DE
)
)
)
)
new Json:
{"version":"0","roles":{"customer":[]},"person":{"firstName":"Inge","lastName":"Musterfrau"},"emailAddresses":{"private":["email#domain.com"]},"addresses":{"billing":[{"supplement":"","street":"aaa","zip":"12345","city":"Berlin","countryCode":"DE"}]}}
Building arrays can be very simple this way - almost feels linear! :)

Transpose subarray data from indexed to associative

I'm making an API for getting some data. My API gives object data like given, given object I wanted to format some data inside object:
{
"data": [
{
"productId": 55,
"productTitle": "Test product",
"variation": {
"Color": "Red",
"Size": "XS",
"din": "10190537",
"product_id": 55,
"name": [
"Color",
"Size"
],
"value": [
"Red",
"XS"
]
},
"din": "10190537",
"markets": [
{
"id": 11,
"name": "paytmmall",
"displayName": "PayTm Mall",
"identifierName": "Product_Id"
}
]
}
]
}
In this object I want data like given
{
"data": [
{
"productId": 55,
"productTitle": "this is test from hariom",
"variation": {
"Color": "Red",
"Size": "XS",
"din": "10190537",
"product_id": 55,
"variationTypes": [
{
"name": "Color",
"value": "Red"
},
{
"name": "Size",
"value": "XS"
}
],
},
"din": "10190537",
"markets": [
{
"id": 11,
"name": "paytmmall",
"displayName": "PayTm Mall",
"identifierName": "Product_Id"
}
]
}
]
}
Here Is my Controller Name
public function MarketMapping(Request $request)
{
$sellerId = Auth::guard('seller-api')->user();
$page = $request->has('pageNumber') ? $request->get('pageNumber') : 1;
$limit = $request->has('perPage') ? $request->get('perPage') : 10;
$variationFromInvTbl = ProductInventory::select('Color', 'Size', 'din', 'product_id')->where('seller_id', $sellerId->id)->where('status', 'active')->limit($limit)->offset(($page - 1) * $limit)->get();
$dataArray = array();
foreach($variationFromInvTbl as $key => $varitionValue)
{
$prodtsFromLivetbl = ProductsLive::select('productTitle', 'product_id')->where('product_id', $varitionValue->product_id)->get();
foreach ($prodtsFromLivetbl as $key => $value)
{
$marketChannelData = DB::table('market_channels')
->join('sellers_market_channels', 'market_channels.name', '=', 'sellers_market_channels.key')
//->join('market_product_mappings', 'market_channels.id', '=', 'market_product_mappings.market_id')
->select('market_channels.id','market_channels.name', 'market_channels.displayName','market_channels.identifierName') //'market_product_mappings.identifierValue'
->where('sellers_market_channels.seller_id', $sellerId->id)
->where('sellers_market_channels.value', 1)
->get();
$maketProductMap = MarketProductMapping::where('seller_id', $sellerId->id)->where('product_id', $varitionValue->product_id)->where('din', $varitionValue->din)->pluck('identifierValue');
if (count($maketProductMap))
{
$marketChannelData[$key]->value = $maketProductMap[0];
}
$varitionValue['name']= array_keys($varitionValue->only(['Color', 'Size']));
$varitionValue['value'] = array_values($varitionValue->only(['Color', 'Size']));
$dataObject = ((object)[
"productId" => $value->product_id,
"productTitle" => $value->productTitle,
"variation" => $varitionValue,
"din" => $varitionValue['din'],
"markets" => $marketChannelData
]);
array_push($dataArray,$dataObject);
}
}
if($variationFromInvTbl)
{
$response['success'] = true;
$response["page"] = $page;
$response["itemPerPage"] = $limit;
$response["totalRecords"] = $this->CountMarketMapping($page, $limit, $sellerId->id);
$response['data'] = $dataArray;
return response()->json($response, 200);
}else{
$response['success'] = false;
$response['data'] = $prodtsFromLivetbl;
return response()->json($response, 409);
}
}
You are using laravel's only() method which returns an associative array.
You wish to convert each key-value pair into a subarray containing two associative elements -- the original key will be the value of the name element
and the original value will be the value of the value element.
By passing the original array keys and array values into array_map(), you can iterate them both synchronously.
compact() is a perfect native function to create the desired associative subarrays from the iterated parameters.
Code: (Demo)
$variations = $varitionValue->only(['Color', 'Size']);
$dataObject = (object)[
// ... your other data
'variations' => array_map(
function($name, $value) {
return compact(['name', 'value']);
},
array_keys($variations),
$variations
),
// ...your other data
];
var_export($dataObject);
Output:
(object) array(
'variations' =>
array (
0 =>
array (
'name' => 'Color',
'value' => 'Red',
),
1 =>
array (
'name' => 'Size',
'value' => 'XS',
),
),
)
This script will help you
<?php
$data = [
"variation" => [
[
"Color" => "Red",
"Size" => "XS",
"din" => "10190537",
"product_id" => 55,
"name" => [
"0" => "Color",
"1" => "Size"
],
"value" => [
"0" => "Red",
"1" => "XS"
]
]
]
];
for ($i=0; $i < count($data["variation"]); $i++) {
$data["variation"][$i]["data"]["name"] = $data["variation"][$i]["name"];
$data["variation"][$i]["data"]["value"] = $data["variation"][$i]["value"];
unset($data["variation"][$i]["name"]);
unset($data["variation"][$i]["value"]);
}
print_r($data);
output
Array
(
[variation] => Array
(
[0] => Array
(
[Color] => Red
[Size] => XS
[din] => 10190537
[product_id] => 55
[data] => Array
(
[name] => Array
(
[0] => Color
[1] => Size
)
[value] => Array
(
[0] => Red
[1] => XS
)
)
)
)
)

In PHP, how do you output JSON iterating first on a child array, then on parent?

I have tried for several weeks to get this to work, and have given in. I need to display the following array in JSON.
As you can see, [coloroptions] is itself a JSON array, making this a multidimensional array. The trick is (I think) to iterate over the array, first on the child [coloroptions], then on the parent. I am probably way off base, though. Has anyone done anything like this?
Thank you, in advance!
SAMPLE DATA from print_r()
Array
(
[0] => Array
(
[id] => 1
[automobile] => 'Mustang'
[coloroptions] => [{"color":"red"},{"color":"blue"},{"color":"green"}]
)
[1] => Array
(
[id] => 2
[automobile] => 'Camero'
[coloroptions] => [{"color":"red"},{"color":"orange"}]
)
)
JSON output
[
{
"id": 1,
"automobile": "Mustang",
"color": "red"
},
{
"id": 1,
"automobile": "Mustang",
"color": "blue"
},
{
"id": 1,
"automobile": "Mustang",
"color": "green"
},
{
"id": 2,
"automobile": "Camero",
"color": "red"
},
{
"id": 2,
"automobile": "Camero",
"color": "orange"
},
]
I think you're close! My approach would be to use json_decode on the colours, and iterate over them like a normal PHP array.
// First, start by looping through each 'parent':
foreach($array as $key => $value)
{
// Decode the json color array into a normal php array
$colorarray = json_decode($value['coloroptions'], true);
/* Loop through each of the colours.
(Note that they'll be a few layers deep.
Do a print_r($colorarray) to see it's structure) */
foreach($colorarray as $color)
{
// And build your output array:
$output[] = array(
"id" => $value['id'],
"automobile" => $value['automobile'],
"color" => $color['color']
);
}
}
To check the final PHP array you can print_r($output). To convert $output into a json array, use json_encode
json_encode($output);
Well , you need to json_decode the coloroptions and output the assembled array with colors inside it to the result array.
$a = array(
array(
'id' => 1,
'automobile' => 'Mustang',
'coloroptions' => '[{"color":"red"},{"color":"blue"},{"color":"green"}]'
),
array(
'id' => 2,
'automobile' => 'Camero',
'coloroptions' => '[{"color":"red"},{"color":"orange"}]'
),
);
$result = array();
foreach($a as $key => $value) {
$coloroptions = json_decode($value['coloroptions']);
foreach($coloroptions as $color){
$result[] = array(
'id' => $value['id'],
'automobile' => $value['automobile'],
'color' => $color->color,
);
}
}
print_r(json_encode($result));
see the example here

How can I recreate this JSON array in PHP?

I have an array in JSON that I need to recreate in PHP.
{
"items": {
"category": "fruit",
"detail": [
{
"name": "apple",
"good": true
}
]
}
"moreItems": {
"category": "fruit",
"detail": [
{
"name": "banana",
"good": false
}
]
}
}
My hopes are to create this using PHP arrays, then json_encode it.
I've tried to set the array above to a string, and de_coded it, but I'm not getting anywhere.
Thanks.
in PHP
$arr = array("items" => array(
0 => array (
"category" => "fruit",
"detail" => array("name" => "apple", "good" => true )
)
),
"moreItems" => array(
0 => array (
"category" => "fruit",
"detail" => array("name" => "banana", "good" => false)
)
)
);
or for manual assignment that maybe useful if using loops:
$arr["items"]["category"] = "fruit";
$arr["items"]["detail"][0]["name"] = "apple";
$arr["items"]["detail"][0]["good"] = true;
$arr["moreItems"]["category"] = "fruit";
$arr["moreItems"]["detail"][0]["name"] = "banana";
$arr["moreItems"]["detail"][0]["good"] = false;
echo json_encode($arr);
will give you the same output..
Actual output in JSON
Cheers!
If you have a json (in PHP) as a string, and you want to convert them to a native PHP array you can easy do that:
<?php
function objectToArray( $object )
{
if( !is_object( $object ) && !is_array( $object ) )
{
return $object;
}
if( is_object( $object ) )
{
$object = get_object_vars( $object );
}
return array_map( 'objectToArray', $object );
}
$json = '{\
"items": {\
"category": "fruit",\
"detail": [\
{\
"name": "apple",\
"good": true\
}\
]\
}\
"moreItems": {\
"category": "fruit",\
"detail": [\
{\
"name": "banana",\
"good": false\
}\
]\
}\
}';
$array = objectToArray( json_decode($json) );
echo "<pre>".print_r($array, true)."</pre>";
That's it!
Thanks to Michael Berkowski, this worked for me. You can recreate the nested [] in the code below.
If you want to replicate the structure more truly, forcing PHP to use
stdClass objects instead of assoc arrays, you might cast the inner
ones to objects: 'detail' => array(0 => (object)array('name' =>
'banana', 'good' => false))
This below will do just fine for me.
$phpArray = array(
"items" => array(
"category" => "fruit",
"detail" => array(
0 => array(
"name" => "apple", "good" => true
)
)
),
"moreItems" => array(
"category" => "fruit",
"detail" => array(
0 => array(
"name" => "banana",
"good" => false
)
)
)
);

Converting php object to json

I've a php object that I want to convert to the following json format.
All the data values are object via a php object in the format:
Array ( [0] => stdClass Object ( [id] => 2
[s1] => 1485
[name] => 1485
[credit] => ''
[caption] => ''
)
)
I'm trying to group the credit, caption, etc. under child. Also, I'm unable to get the [ after date in the json format.
{
"mydata":
{
"name":Name,
"type":"default",
"date": [
{
"s1":"1485",
"name":"1485",
"child":
{
"credit":"",
"caption":""
}
}]
}
}
Currently, my code looks like:
foreach ($hits as $hit) {
$data->mydata->date->s1 = $hit->s1;
$data->mydata->date->name = $hit->name;
$data->mydata->date->credit = $hit->credit;
$data->mydata->date->caption = $hit->caption;
}
$a = json_encode($data);
set $date->mydata->date to an array and you will get the []
And why not making more nested structures?
The JSON format you're looking at shows that date is an array (the brackets are array notation in javascript), so:
<?php
$var = array(
'mydata' => array(
'name' => 'Name',
'type' => 'default',
'date' => array(
array(
's1' => 1485,
'name' => '1485',
'child' => array(
'credit' => '',
'caption' => '',
),
),
),
),
);
print json_encode($var);
prints out:
{
"mydata": {
"name": "Name",
"type": "default",
"date": [
{
"s1": 1485,
"name": "1485",
"child": {
"credit": "",
"caption": ""
}
}
]
}
}
No need to try and add stdClass instances or anything like that in PHP. Just build out a nice clean array and JSON encode will convert to object properties and arrays where necessary.

Categories