How do you manipulate the output using json_encode? - php

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

Related

Display data from two arrays having one common point

I have two arrays.
The first one is about exchange-rate and the display in my console is like this :
{
"exchange_rate": [
{
"id": "978",
"start_dateTime": "2021-08-01 07:35:02",
"target_value": "1.00000",
"currency_value_euro": "0.84097",
"currency_value_dollar_us": "1.00000",
"id_currency": "1",
"currency": "Dollar am\u00e9ricain",
"currency_symbol": "$US"
},
{
"id": "980",
"start_dateTime": "2021-08-01 07:35:02",
"target_value": "1.00000",
"currency_value_euro": "1.17454",
"currency_value_dollar_us": "0.71600",
"id_currency": "2",
"currency": "Livre sterling",
"currency_symbol": "\u00a3"
}
]
}
These data came from the database and I can display it by choosing particular dates with jQuery.
The second array contains only id_currency which in my console is like this : Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5
On my website, I want to be able to display specific exchange rate by specific currency and dates.
And here my problem appears, I can't find the way to loop on the first array, and loop again inside, on the second array and compare both like if first array has id_currency 1 and second array has id_currency 1 then display the complete line from first array.
I've tried several things but nothing works, at last i've tried this :
foreach ($res as $row){
$idBDD = $row['id_currency'];
$symbolBDD = $row['currency_symbol'];
echo $idBDD;
echo $symbolBDD;
//var_dump($row);
/*foreach ($arr as $line){
$idCheckbox = $line;
echo $idCheckbox;
}
if ($idBDD == $idCheckbox){
echo 'fine';
}
*/
}
I'll be grateful for your help
You need to access the array with $res["exchange_rate"] and loop through it then.
<?php
$res = [
"exchange_rate" => [
[
"id" => "978",
"start_dateTime" => "2021-08-01 07:35:02",
"target_value" => "1.00000",
"currency_value_euro" => "0.84097",
"currency_value_dollar_us" => "1.00000",
"id_currency" => "1",
"currency" => "Dollar américain",
"currency_symbol" => "\$US"
],
[
"id" => "980",
"start_dateTime" => "2021-08-01 07:35:02",
"target_value" => "1.00000",
"currency_value_euro" => "1.17454",
"currency_value_dollar_us" => "0.71600",
"id_currency" => "2",
"currency" => "Livre sterling",
"currency_symbol" => "£"
]
]
];
$output = null;
foreach ($res["exchange_rate"] as $row) {
if (!isset($output)) {
$output = $row;
}
$output = array_intersect_assoc($output, $row);
}
var_dump($output);
I think you could do it like this, of course if you're inside the loop, you won't need to put indices.
read more array_diff()
https://www.php.net/manual/pt_BR/function.array-diff.php
$array = [
"exchange_rate" => [
[
"id" => "978",
"start_dateTime" => "2021-08-01 07:35:02",
"target_value"=> "1.00000",
"currency_value_euro"=> "0.84097",
"currency_value_dollar_us"=> "1.00000",
"id_currency"=> "1",
"currency"=> "Dollar am\u00e9ricain",
"currency_symbol" => "US"
],[
"id"=> "980",
"start_dateTime"=> "2021-08-01 07=> 35=> 02",
"target_value"=> "1.00000",
"currency_value_euro"=> "1.17454",
"currency_value_dollar_us"=> "0.71600",
"id_currency"=> "2",
"currency"=> "Livre sterling",
"currency_symbol"=> "\u00a3"
]
]
];
$array1 = $array['exchange_rate'][0];
$array2 = $array['exchange_rate'][1];
$result = array_diff( $array1, $array2);
var_dump($result);

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

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

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

Create a array for this json in php

I want to create a array for the following json code.
{
"homeMobileCountryCode": 310,
"homeMobileNetworkCode": 260,
"radioType": "gsm",
"carrier": "T-Mobile",
"cellTowers": [
{
"cellId": 39627456,
"locationAreaCode": 40495,
"mobileCountryCode": 310,
"mobileNetworkCode": 260,
"age": 0,
"signalStrength": -95
}
],
"wifiAccessPoints": [
{
"macAddress": "01:23:45:67:89:AB",
"signalStrength": 8,
"age": 0,
"signalToNoiseRatio": -65,
"channel": 8
},
{
"macAddress": "01:23:45:67:89:AC",
"signalStrength": 4,
"age": 0
}
]
}
I have tried with the following but it is showing parsing error in google maps geomatic api
$a = array("homeMobileCountryCode" => 310,
"homeMobileNetworkCode" => 260,
"radioType" => "gsm",
"carrier" => "T-Mobile");
$jsonVal = json_encode($a);
can anyone help me?
PHP's json_encode does not wrap integers with double quotes, which is invalid json. Try this:
$a = array("homeMobileCountryCode" => "310",
"homeMobileNetworkCode" => "260",
"radioType" => "gsm",
"carrier" => "T-Mobile");
$jsonVal = json_encode($a);
From json to Array:
$array = json_decode(/* json text /*);
From Array to Json
$json = json_encode(/* array Object */);
explanations here but you can skip to clean final code further down.
$cellTower1 = array( "cellId"=> "39627456",
"locationAreaCode"=> "40495",
"mobileCountryCode"=> "310",
"mobileNetworkCode"=> "260",
"age"=> "0",
"signalStrength"=> "-95" );
$cellTower2 = array( "cellId"=> "2222222",
"locationAreaCode"=> "22222",
"mobileCountryCode"=> "222",
"mobileNetworkCode"=> "222",
"age"=> "22",
"signalStrength"=> "-22" );
Then combine all cell towers
$allCellTowers[] = $cellTower1;
$allCellTowers[] = $cellTower2;
//etc... or could be in a loop
Now for MAC addresses and wifiAccessPoints.
$macAddress1 = array (
"macAddress"=> "01:23:45:67:89:AB",
"signalStrength" => "8",
"age" => "0",
"signalToNoiseRatio" => "-65",
"channel" => "8"
);
$macAddress2 = array (
"macAddress" => "01:23:45:67:89:AC",
"signalStrength" => "4",
"age" => "0"
);
$macAddress3 = etc...
just as for cellTower1, cellTower2 the macaddresses 1 & 2 above can be populated with a loop.
Adding them to wifiAccessPoints also can be done in a loop but it done manually below just so you understand.
$wifiAccessPoints[] = $macAddress1;
$wifiAccessPoints[] = $macAddress2;
finally the other elements all go in the resulting array to encode
$myarray = array( "homeMobileCountryCode"=> "310",
"homeMobileNetworkCode"=> "260",
"radioType"=> "gsm",
"carrier"=> "T-Mobile",
"cellTowers"=>$allCellTowers,
"wifiAccessPoints" => $wifiAccessPoints
);
$json = json_encode($myarray);
IN CLEAN CODE IT IS
$cellTower1 = array( "cellId"=> "39627456",
"locationAreaCode"=> "40495",
"mobileCountryCode"=> "310",
"mobileNetworkCode"=> "260",
"age"=> "0",
"signalStrength"=> "-95" );
$allCellTowers[] = $cellTower1;
$macAddress1 = array (
"macAddress"=> "01:23:45:67:89:AB",
"signalStrength" => "8",
"age" => "0",
"signalToNoiseRatio" => "-65",
"channel" => "8"
);
$macAddress2 = array (
"macAddress" => "01:23:45:67:89:AC",
"signalStrength" => "4",
"age" => "0"
);
$wifiAccessPoints[] = $macAddress1;
$wifiAccessPoints[] = $macAddress2;
$myarray = array( "homeMobileCountryCode"=> "310",
"homeMobileNetworkCode"=> "260",
"radioType"=> "gsm",
"carrier"=> "T-Mobile",
"cellTowers"=>$allCellTowers,
"wifiAccessPoints" => $wifiAccessPoints
);
//note that you have your first key missing though in your example
$json = json_encode($myarray);

Categories