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);
Related
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);
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
)
)
)
)
)
I'm trying to make JSON to send it to webservice. Final json should looks like:
{
"name": "Pravidlo",
"partQualities": [
"A",
"O",
"N"
],
"residualValueMax": 100,
"residualValueMin": 0,
"selectionStrategy": "MIN_PRICE",
"suppliers": [
864,902,903,907,910,911,913,914,915,916,917,957
],
"vehicleAgeMax": 100,
"vehicleAgeMin": 0
}
What I did try:
$data = array (
"name" => "Pravidlo",
"partQualities" => array(
'A', 'O', 'N'
),
"residualValueMax" = "100",
"residualValueMin" = "0",
"selectionStrategy" = "MIN_PRICE",
"suppliers" = array(
864,902,903,907,910,911,913,914,915,916,917,957
),
"vehicleAgeMax" = "100",
"vehicleAgeMin" = "0"
);
// json encode data
$data_string = json_encode($data);
How Ever I'm getting error with "unexpect" = between residualValueMax and 100.
Can someone please advise me how to create JSON like that ?
Thanks
You need to replace the = with => in the array declaration.
Use => and not = for an array.
foreach ($ordersList as $object) {
$entityid = $object->entity_id; //how to give this $entityid with in json
$json='{
"orderNo":$entityid, //here i want to assign the value of $entityid
"customerCode": $customerid,
"dateOrdered": "08-07-2015",
"warehouseId" : ,
"orderLineList":
[
"productId": 1000002,
"qty": 6,
"price": 10
]
}';
}
$data = json_decode($json);
$data_string= json_encode($data);
Don't write JSON strings by hand.
$data = [
"orderNo" => $entityid, //here i want to assign the value of $entityid
"customerCode" => $customerid,
"dateOrdered" => "08-07-2015",
"warehouseId" => null ,
"orderLineList" => [
"productId": 1000002,
"qty": 6,
"price": 10,
],
];
$json = json_encode($data);
json_decode() would give an error for this:
{"orderLineList": [ "productId": 1000002 ]}
Try this code:
foreach ($ordersList as $object) {
//Start with a PHP array
//Don't mess with concatenation, you will get tangled with opening & closing quotes.
//If your information comes in a json format. Use json_decode() to convert it into a PHP array.
//$dateOrder,$warehouseId,$object->customer_id are fictious variables. Replace them with real values.
$orderArray[] = [
'orderNo' => $object->entity_id,
'customerCode' => $object->customer_id,
'dateOrdered' => $dateOrdered,
'warehouseId' => $warehouseId,
'orderLineList' => [
'productId': 1000002,
'qty': 6,
'price': 10
]
];
}
$data_string = json_encode($orderArray);
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'
)
);