How can I recreate this JSON array in PHP? - 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
)
)
)
);

Related

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
)
)
)
)
)

How to remove array of object in PHP

<?php
$test = '{
"100": {
"name": "Sports",
"contentID": "100"
},
"200": {
"name": "Village",
"contentID": "200"
}
}';
$idWiseData = json_decode($test,true);
$test2 = '[
{
"contentID": "100",
"contentStatus": "active"
},
{
"contentID": "200",
"contentStatus": "active"
},
{
"contentID": "300",
"contentStatus": "active"
}
]';
$allTopics = json_decode($test2,true);
foreach ($allTopics as $key => &$topic) {
$contentInfo = [
'contentStatus' => $topic['contentStatus']
];
$topic['contentName'] = isset($idWiseData[$topic['contentID']]['name']) ? $idWiseData[$topic['contentID']]['name'] : null;
}
echo "<pre>";
print_r($allTopics);
?>
Above code is working fine, i am not getting my expected output. actually $allTopics having 3 objects (contentID 100 & 200 & 300).$idWiseData having object (contentID 100 & 200).
I want to take name value from $idWiseData and replace to $allTopics based on contentID.
contentID 300 don't have name so should not come this object.
Expected out put
Array
(
[0] => Array
(
[contentID] => 100
[contentStatus] => active
[contentName] => Sports
)
[1] => Array
(
[contentID] => 200
[contentStatus] => active
[contentName] => Village
)
)
I am getting output
Array
(
[0] => Array
(
[contentID] => 100
[contentStatus] => active
[contentName] => Sports
)
[1] => Array
(
[contentID] => 200
[contentStatus] => active
[contentName] => Village
)
[2] => Array
(
[contentID] => 300
[contentStatus] => active
[contentName] =>
)
)
Kindly anyone update my code please.
As far as I understand you, you need to unset() the index within the array if contentName is null. This can be achieved by using unset()
foreach ($allTopics as $key => &$topic) {
// your code here ....
if (is_null($topic['contentName'])) {
unset(allTopics[$key]);
}
}
You can remove a record from the array by using array_slice. But I would recommend you to change your code and have a 3rd array which must be your result, so then you don't need to change any of your source data.
You're not deleting the index from the array just setting contentName to null. Use unset to delete the index from the array.
Try this one:
<?php
$test = '{
"100": {
"name": "Sports",
"contentID": "100"
},
"200": {
"name": "Village",
"contentID": "200"
}
}';
$idWiseData = json_decode($test,true);
$test2 = '[
{
"contentID": "100",
"contentStatus": "active"
},
{
"contentID": "200",
"contentStatus": "active"
},
{
"contentID": "300",
"contentStatus": "active"
}
]';
$allTopics = json_decode($test2,true);
foreach ($allTopics as $key => &$topic) {
$contentInfo = [
'contentStatus' => $topic['contentStatus']
];
if(isset($idWiseData[$topic['contentID']]['name'])){
$topic['contentName'] = $idWiseData[$topic['contentID']]['name'];
} else {
unset($allTopics[$key]);
}
}
echo "<pre>";
print_r($allTopics);
?>
foreach ($allTopics as $key => &$topic) {
$contentInfo = [
'contentStatus' => $topic['contentStatus']
];
$topic['contentName'] = isset($idWiseData[$topic['contentID']]['name']) ? $idWiseData[$topic['contentID']]['name'] : null;
if (is_null($topic['contentName'])) {
unset($topic['contentName']);
}
}
USE THIS CODE THIS MIGHT SOLVE YOUR PROBLEM.

PHP wrap array elements in separate arrays

I have the following array:
$arr = [
"elem-1" => [ "title" => "1", "desc" = > "" ],
"elem-2" => [ "title" => "2", "desc" = > "" ],
"elem-3" => [ "title" => "3", "desc" = > "" ],
"elem-4" => [ "title" => "4", "desc" = > "" ],
]
First I need to change the value from [ "title" => "1", "desc" = > "" ] to 1 (title's value).
I did this using array_walk:
array_walk($arr, function(&$value, $key) {
$value = $value["title"];
});
This will replace my value correctly. Our current array now is:
$arr = [
"elem-1" => "1",
"elem-2" => "2",
"elem-3" => "3",
"elem-4" => "4",
]
Now, I need to transform each element of this array into its own subarray. I have no idea on how to do this without a for loop. This is the desired result:
$arr = [
[ "elem-1" => "1" ],
[ "elem-2" => "2" ],
[ "elem-3" => "3" ],
[ "elem-4" => "4" ],
]
You can change your array_walk callback to produce that array.
array_walk($arr, function(&$value, $key) {
$value = [$key => $value["title"]];
});
Run the transformed array through array_values if you need to get rid of the string keys.
$arr = array_values($arr);
To offer an alternative solution you could achieve all of this with array_map
<?php
$arr = [
"elem-1" => [ "title" => "1", "desc" => "" ],
"elem-2" => [ "title" => "2", "desc" => "" ],
"elem-3" => [ "title" => "3", "desc" => "" ],
"elem-4" => [ "title" => "4", "desc" => "" ],
];
function convertToArray($key,$elem){
return [$key => $elem['title']];
}
$arr = array_map("convertToArray", array_keys($arr), $arr);
echo '<pre>';
print_r($arr);
echo '</pre>';
?>
outputs
Array
(
[0] => Array
(
[elem-1] => 1
)
[1] => Array
(
[elem-2] => 2
)
[2] => Array
(
[elem-3] => 3
)
[3] => Array
(
[elem-4] => 4
)
)
It doesn't make much sense to use array_walk() and modify by reference because the final result needs to have completely new keys on both levels. In other words, the output structure is completely different from the input and there are no salvageable/mutable parts. Mopping up the modified array with array_values() only adds to the time complexity cost.
array_map() has to bear a cost to time complexity too because array_keys() must be passed in as an additional parameter.
If you want to use array_walk(), use use() to modify the result array. This will allow you to enjoy the lowest possible time complexity.
More concise than array_walk() and cleaner to read, I would probably use a classic foreach() in my own project.
Codes: (Demo)
$result = [];
array_walk(
$arr,
function($row, $key) use(&$result) {
$result[] = [$key => $row['title']];
}
);
Or:
$result = [];
foreach ($arr as $key => $row) {
$result[] = [$key => $row['title']];
}
var_export($result);
You need to use array_map like
$new_arr= array_map(function($key,$val){
return [$key => $val['title']];},array_keys($arr),$arr);

Use array_filter on multi dimensional array

I'm trying to filter an array that looks like this
$array = array(
"id" => "SomeID",
"name" => "SomeName",
"Members" => array(
"otherID" => "theValueIamLookingFor",
"someOtherKey" => "something"
)
);
Now, I'm filtering for data sets, where "otherID" is a certain value. I know I could use array_filter to filter for "id", but I can't for the life of me figure out how to filter for a value in an array inside an array.
Adding some of the data as provided by the WebAPI (I run that through json_decode to create an associative array before all this filtering business)
[
{
"id": "b679d716-7cfa-42c4-9394-3abcdged",
"name": "someName",
"actualCloseDate": "9999-12-31T00:00:00+01:00",
"members": [
{
"otherID": "31f27f9e-abcd-1234-aslkdhkj2j4",
"name": "someCompany"
}
],
"competitor": null,
},
{
"id": "c315471f-45678-4as45-457-asli74hjkl",
"name": "someName",
"actualCloseDate": "9999-12-31T00:00:00+01:00",
"members": [
{
"otherID": "askgfas-agskf-as",
"name": "someName"
}
],
"competitor": null,
},
]
You can do something like:
$arr = array(
array(
"id" => "SomeID",
"name" => "SomeName",
"Members" => array (
"otherID" => "ThisIsNottheValueIamLookingFor",
"someOtherKey" => "something"
)
),
array(
"id" => "SomeID",
"name" => "SomeName",
"Members" => array (
"otherID" => "theValueIamLookingFor",
"someOtherKey" => "something"
)
),
array(
"id" => "SomeID",
"name" => "SomeName",
"Members" => array (
"otherID" => "ThisIsNottheValueIamLookingForEither",
"someOtherKey" => "something"
)
),
);
$result = array_filter($arr, function( $v ){
return $v["Members"]["otherID"] == "theValueIamLookingFor";
});
This will result to:
Array
(
[1] => Array
(
[id] => SomeID
[name] => SomeName
[Members] => Array
(
[otherID] => theValueIamLookingFor
[someOtherKey] => something
)
)
)
Here is the doc for more info: http://php.net/manual/en/function.array-filter.php
UPDATE
On you Updated array, the structure of array is different. You have to use $v["members"][0]["otherID"] to get the otherID
Please try the code below:
$result = array_filter($arr, function( $v ){
return $v["members"][0]["otherID"] == "theValueIamLookingFor";
});

How do you manipulate the output using json_encode?

How would I structure $array so that when I pass it to json_encode
$output = json_encode($array);
the output would be:
$output = [
{apples:"33" ,oranges:"22"},
{apples:"44" ,oranges:"11"},
{apples:"55" ,oranges:"66"},
]
Are there any options I need to use to get the output I need? Or is it all about how I structure my PHP array?
This should work for you:
[] = array
{} = object
key:value = key : value
<?php
$array = [
(object)["apples" => "33", "oranges" => "22"],
(object)["apples" => "44", "oranges" => "11"],
(object)["apples" => "55", "oranges" => "66"],
];
echo $output = json_encode($array);
?>
Output:
[
{
"apples": "33",
"oranges": "22"
},
{
"apples": "44",
"oranges": "11"
},
{
"apples": "55",
"oranges": "66"
}
]
You will just need to pass an array of associative arrays to json_encode
$array = array (
array(
'apples'=>'33',
'oranges'=>'22'
),
array(
'apples'=>'44',
'oranges'=>'11'
),
array(
'apples'=>'55',
'oranges'=>'66'
)
);
you can pass with an array of associative arrays in json_encode($var).
$array = array (
array(
'johan'=>'male',
'age'=>'22'
),
array(
'lucy'=>'female',
'age'=>'24'
),
array(
'donald'=>'male',
'age'=>'28'
)
);

Categories