I am creating an associative array from a json code so that i can use in my curl code that connects to an API. Now it seems like the associative array outputted is incorrect. I would like to format it correctly, but now I get message an error saying the array is incorrect.
The json code:
{
"payment": [
{
"clientCorrelator": "54321",
"endUserId": "tel:+16309700001",
"merchantCode": "01234",
"merchantPin": "1234",
"merchantNumber": "tel:+16309700001",
"notifyURL": "http://example.com/notifyURL",
"paymentAmount": {
"chargingInformation": [
{
"amount": "10",
"currency": "USD",
"description": "AlienInvadersGame"
}
],
"chargingMetaData": [
{
"onBehalfOf": "Example Games Inc",
"purchaseCategoryCode": "Game",
"channel": "WAP",
"taxAmount": "0"
}
],
"referenceCode": "REF-12345",
"transactionOperationStatus": "Charged"
}
}
]
}
The php code to build the array:
jasondata = file_get_contents("payment.json");
$json = json_decode($jasondata, true);
$payment = ($json['payment']) ;
print_r($payment);
The output:
Array ( [0] => Array ( [clientCorrelator] => 54321 [endUserId] => tel:+16309700001 [merchantCode] => 01234 [merchantPin] => 1234 [merchantNumber] => tel:+16309700001 [notifyURL] => http://example.com/notifyURL [paymentAmount] => Array ( [chargingInformation] => Array ( [0] => Array ( [amount] => 10 [currency] => USD [description] => AlienInvadersGame ) ) [chargingMetaData] => Array ( [0] => Array ( [onBehalfOf] => Example Games Inc [purchaseCategoryCode] => Game [channel] => WAP [taxAmount] => 0 ) ) [referenceCode] => REF-12345 [transactionOperationStatus] => Charged ) ) )
My main goal is to remove the [0] indexes without messing up the array. please assist
instead of $payment = ($json['payment']);
change that to $payment = reset($json['payment']);
However if there are multiple entries under payment, then you should just loop over them like:
foreach($json['payment'] as $payment){
print_r($payment);
}
The loop also would work if there was any number of elements under payment, so not just multiple.
more or less safe function
$payment = json_decode($str, true);
function RemoveZeroIndex(&$arr) {
foreach($arr as $key => &$item) { // walk array
if (is_array($item) && // if array
(count($item) === 1) && // with one item
isset($item[0])) // and numeric index
$item = $item[0]; // shift it
if (is_array($item))
RemoveZeroIndex($item); // call recursively
}
}
RemoveZeroIndex($payment);
print_r($payment);
In addition to Jonathan Khun.
For your nested arrays you just do the same. Reset the internal pointer of that array.
<?php
$jasondata = '{
"payment": [
{
"clientCorrelator": "54321",
"endUserId": "tel:+16309700001",
"merchantCode": "01234",
"merchantPin": "1234",
"merchantNumber": "tel:+16309700001",
"notifyURL": "http://example.com/notifyURL",
"paymentAmount": {
"chargingInformation": [
{
"amount": "10",
"currency": "USD",
"description": "AlienInvadersGame"
}
],
"chargingMetaData": [
{
"onBehalfOf": "Example Games Inc",
"purchaseCategoryCode": "Game",
"channel": "WAP",
"taxAmount": "0"
}
],
"referenceCode": "REF-12345",
"transactionOperationStatus": "Charged"
}
}
]
}';
$json = json_decode($jasondata, true);
$payment = reset($json['payment']);
$payment['paymentAmount']['chargingInformation'] = reset($payment['paymentAmount']['chargingInformation']);
$payment['paymentAmount']['chargingMetaData'] = reset($payment['paymentAmount']['chargingMetaData']);
echo "<pre>";
print_r($payment);
?>
Related
I have this part of my code which should return modifier options as an array as shown by the json response below but its only returning 1 item.
{
"id": "Add-sugar",
"external_data": "External data for sugar choice",
"title": {
"translations": {
"en_us": "Add sugar"
}
},
"quantity_info": {
"quantity": {
"max_permitted": 2
},
"overrides": []
},
"modifier_options": [
{
"id": "Sugar",
"type": "ITEM"
}
]
},
{
"id": "Add-milk",
"external_data": "External data for milk choice",
"title": {
"translations": {
"en_us": "Add milk"
}
},
"quantity_info": {
"quantity": {
"max_permitted": 1
},
"overrides": []
},
"modifier_options": [
{
"id": "Milk",
"type": "ITEM"
}
]
}
],
Here is my code below. I want it to return an array of modifier options but I'm only getting array with only one modifier option. May you assist me.
if($option->field_active[$language][0]['value'] <> 0 &&
in_array($uber->field_zone[$language][0]['target_id'], array_column($option->field_zones[$language], 'target_id')) &&
in_array("uber_eats", array_column($option->field_viewable[$language], 'value'))){
$optionInd['id'] = $option->id;
$optionInd['external_data'] = $option->id;
$optionInd['title']['translations']['en'] = ucwords(strtolower($option->name));
$optionInd['price_info']['price'] = (int)$option->field_pricelevel4[$language][0]['value'];
if(isset($option->field_default[$language][0]['value'])){
$optionInd['selected_by_default'] = $option->field_default[$language][0]['value'];
}
if (!in_array($optionInd['id'], array_column($groupInd['modifier_options'], 'id'))){
$groupInd['modifier_options'][] = $optionInd;
}
} //end if option Active
}```
if (!in_array($optionInd['id'], array_column($groupInd['modifier_options'], 'id'))){
$groupInd['modifier_options'][] = array(
"id"=> $optionInd['id'],
"type"=> "ITEM");```
$modifier[] = $groupInd;
$menu = array(
'modifier_groups' => $modifier,
);
perhaps this can help? ($result below is modifier_options array)
$data=json_decode( '{"data":[{"id":"Add-sugar","external_data":"External data for sugar choice","title":{"translations":{"en_us":"Add sugar"}},"quantity_info":{"quantity":{"max_permitted":2},"overrides":[]},"modifier_options":[{"id":"Sugar","type":"ITEM"}]},{"id":"Add-milk","external_data":"External data for milk choice","title":{"translations":{"en_us":"Add milk"}},"quantity_info":{"quantity":{"max_permitted":1},"overrides":[]},"modifier_options":[{"id":"Milk","type":"ITEM"}]}]}',true); # define $data as associative array
$result=[];
foreach ($data['data'] as $a){
array_push($result, $a['modifier_options']);
}
print_r($result);
Output:
Array
(
[0] => Array
(
[0] => Array
(
[id] => Sugar
[type] => ITEM
)
)
[1] => Array
(
[0] => Array
(
[id] => Milk
[type] => ITEM
)
)
)
I have been fiddling with JSON nested tag, tried the basics now I want to go a little further, but it has been giving a little head ache to me. I have this public function below
public function returnResponse($code, $data){
header("content-type: application/json");
$result = json_encode(['response' => ['status' => $code, "message" => $data]]);
echo $result ; exit;
}
$order= $cust->getDeliveryDetail();
USING print_r($order);
Array
(
[0] => Array
(
[0] => Array
(
[order_id] => 4444
[menu] => two
[order_uniq] => 999oeo4
)
)
[1] => Array
(
[0] => Array
(
[pro_name] => Beans
[pro_sub] => Goods
[pro_type] => Open CA
)
[1] => Array
(
[pro_name] => Rice
[pro_sub] => Fiber
[pro_type] => Diverca
)
)
)
then attaching object with elements and value which references
$result ['order_id'] = $order[0][0]['order_id'];
$result ['menu'] = $order[0][0]['menu'];
$result ['order_uniq'] = $order[0][0]['order_uniq'];
$result ['pro_name'] = $order[0][0]['pro_name'];
$result ['pro_sub'] = $order[0][0]['pro_sub'];
$result ['pro_type'] = $order[0][0]['pro_type'];
$this->returnResponse(SUCCESS_RESPONSE, $result); //THIS IS THE ORIGINAL BEGINNING PUBLIC FUNCTION WE CREATED
to create this JSON nested tag below
{
"response": {
"status": 200,
"message": {
"order_id": "4444",
"menu": "two",
"order_uniq": "999oeo4",
"pro_name": "Beans",
"pro_sub": "Goods",
"pro_type": "Openca",
}
}
}
but I want to create a JSON nested tag like this below
{
"response": {
"status": 200,
"message": {
"order_id": "4444",
"menu": "two",
"order_uniq": "999oeo4",
"items": [
{
"pro_name": "Beans",
"pro_sub": "Goods",
"pro_type": "Openca",
}
{
"pro_name": "Rice",
"pro_sub": "Fiber",
"pro_type": "Diverca",
}
]
},
}
}
If it helps -- maybe not, the right way to do this in the beginning would be to create an OrderItems table/dictionary. Then store items in that table referrencing your Order table with "order_id". That way you could pull order_items as one array object, and convert that to json really simply.
Here since, you are getting "pro_name", "pro_sub" & "pro_type" as items, you would programmatically pull those out and create your own order_items array.
$order= $cust->getDeliveryDetail();
$order_id = $order[0][0]['order_id'];
$order_menu = $order[0][0]['menu'];
$order_uniq = $order[0][0]['order_uniq'];
$items = [];
foreach($order[1] as $order_item) {
$items[] = $order_item;
}
$result = [];
$result["order_id"] = $order_id;
$result["menu"] = $order_menu;
$result["order_uniq"] = $order_uniq;
$result["order_items"] = $items;
$this->returnResponse(SUCCESS_RESPONSE, $result);
Like this?
$result = array(
'order_id' = > $order[0][0]['order_id'],
'menu' => $order[0][0]['menu'],
'order_uniq' => $order[0][0]['order_uniq'],
'pro_name' => $order[0][0]['pro_name'],
'pro_sub' => $order[0][0]['pro_sub'],
'pro_type' => $order[0][0]['pro_type'],
'items' => array()
);
foreach($order[1] as $item) {
array_push(
$result['items'],
array(
'pro_name' => $item['pro_name'],
'pro_sub' => $item['pro_sub'],
'pro_type' => $item['pro_type'],
)
);
}
I have the below code in a for..loop is there a way I can add values to the beginning of the array?
$data = array();
$initial = strtotime('11:00:00');
for (; $initial < strtotime("23:00:59"); $initial = strtotime("+15 minutes", $initial)) {
if ($initial > strtotime("+45 minutes", time())) {
$row['value'] = date('Hi', $initial);
$row['label'] = date('H:i', $initial);
$data['data'][] = $row;
}
}
I want to add the below values to the top of the array. I have tried using array_unshift but I don't think it supports key-value pairs.
if(!isBetween('22:00', '09:59', date('H:i'))) {
$row['value'] = "asap";
$row['label'] = "ASAP";
}
My array output
{
"data": [
{
"value": "1145",
"label": "11:45"
}
]
}
I want to get this
{
"data": [
{
"value": "asap",
"label": "ASAP"
},{
"value": "1145",
"label": "11:45"
},
]
}
Un-shift should work if you pass the arguments correctly:
array_unshift($data["data"], $prepend);
Alternatively, you could use array_merge, like this:
$data["data"] = array_merge(array($prepend), $data["data"]);
With the following example data:
$data = [
"data" => [
[
"value" => "1145",
"label" => "11:45"
]
]
];
$prepend = [
"value" => "asap",
"label" => "ASAP"
];
$data["data"] = array_merge(array($prepend), $data["data"]);
print_r($data);
You would get this output (with both solutions):
Array (
[data] => Array (
[0] => Array (
[value] => asap
[label] => ASAP
)
[1] => Array (
[value] => 1145
[label] => 11:45
)
)
)
If you need to prepend something to the array without the keys being reindexed and/or need to prepend a key value pair, you can use this short function:
function array_unshift_assoc(&$arr, $key, $val) {
$arr = array_reverse($arr, true);
$arr[$key] = $val;
return array_reverse($arr, true);
}
Source: http://php.net/manual/en/function.array-unshift.php
Array Values to assign the variables in php:
Array
(
[0] => stdClass Object
(
[Id] => 116249
[Amount] => 51.62
[Currency] => INR
[ExchangeRate] => 1
[InvoiceDate] => 2015-12-16T00:00:00Z
}
[1] => stdClass Object
(
[Id] => 116250
[Amount] => 55.20
[Currency] => KWD
[ExchangeRate] => 1
[InvoiceDate] => 2015-12-16T00:00:00Z
}
[2] => stdClass Object
(
[Id] => 116251
[Amount] => 59.42
[Currency] => USD
[ExchangeRate] => 1
[InvoiceDate] => 2015-12-16T00:00:00Z
}
}
foreach ($invoice as $key => $value)
{
$Id=$value->Id;
$Amount=$value->Amount;
$Currency=$value->Currency;
$ExchangeRate=$value->ExchangeRate;
$invoiceDate = str_replace('Z', '', str_replace('T', ' ',$value->InvoiceDate));
}
$jsonData ='[{"Id": "'.$Id.'",
"Amount": "'.$Amount.'",
"Currency": "'.$Currency.'",
"ExchangeRate": "'.$ExchangeRate.'",
"invoiceDate": "'.$invoiceDate.'"}];
I tried this code last array values only print array[2] values, I need Output like
[{"Id": "116249",
"Amount": "51.62",
"Currency": "INR",
"ExchangeRate": "1",
"invoiceDate": "2015-12-16T00:00:00Z"},
{"Id": "116250",
"Amount": "55.20",
"Currency": "KWD",
"ExchangeRate": "1",
"invoiceDate": "2015-12-16T00:00:00Z"},
{"Id": "116251",
"Amount": "59.42",
"Currency": "USD",
"ExchangeRate": "1",
"invoiceDate": "2015-12-16T00:00:00Z"}]
I agree with Liam that json_encode() is probably the best solution for your issue. However, if you are looking for a DIY solution, it's pretty simple:
$jsonData = '[';
foreach ($invoice as $key => $value)
{
$Id=$value->Id;
$Amount=$value->Amount;
$Currency=$value->Currency;
$ExchangeRate=$value->ExchangeRate;
$invoiceDate = str_replace('Z', '', str_replace('T', ' ',$value->InvoiceDate));
// Append the next invoice's JSON data to all of the JSON data
$jsonData .='{"Id": "'.$Id.'",
"Amount": "'.$Amount.'",
"Currency": "'.$Currency.'",
"ExchangeRate": "'.$ExchangeRate.'",
"invoiceDate": "'.$invoiceDate.'"},';
}
// Clean up and close off the JSON data:
$jsonData = rtrim($jsonData, ','); // remove the trailing comma
$jsonData .= ']'; // Add the closing bracket.
The issue you were having in your code was that you were only assigning the JSON data once, after the foreach loop ran. Instead, you would need to append each invoice's JSON data with the other invoices' JSON data.
Nonetheless, json_encode() is probably the better solution because it's one line, easier to read, and arguably easier to understand.
Your wanting to create a json string from an array. All you need to do is run the following
jsonData = json_encode($invoice);
If your wanting to create the array using a loop to generate specific values only then you can do the following:
$tmp = array();
foreach ($invoice as $key => $value)
{
$tmp["id"] = $value->Id;
$tmp["amount"] = $value->Amount;
$tmp["Currency"] = $value->Currency;
$tmp["ExchangeRate"] = $value->ExchangeRate;
$tmp["invoiceDate"] = str_replace('Z', '', str_replace('T','',$value->InvoiceDate));
}
jsonData = json_encode($tmp);
* Edit *
If your using a mysql date for the invoiceData variable. Then you would be better to use the PHP date function.
i am getting this request.
{ "area": [
{
"area": "kothrud"
},
{
"area": "katraj"
}
]
}
and i want to provide response to this by searching records in database based on above request. how will i decode above json array and use each area field separately.
your string is NOT a valid json to start with.
a valid json will be,
{
"area": [
{
"area": "kothrud"
},
{
"area": "katraj"
}
]
}
if you do a json_decode, it will yield,
stdClass Object
(
[area] => Array
(
[0] => stdClass Object
(
[area] => kothrud
)
[1] => stdClass Object
(
[area] => katraj
)
)
)
Update: to use
$string = '
{
"area": [
{
"area": "kothrud"
},
{
"area": "katraj"
}
]
}
';
$area = json_decode($string, true);
foreach($area['area'] as $i => $v)
{
echo $v['area'].'<br/>';
}
Output:
kothrud
katraj
Update #2:
for that true:
When TRUE, returned objects will be converted into associative arrays. for more information, click here
you can use json_decode function
foreach (json_decode($response) as $area)
{
print_r($area); // this is your area from json response
}
See this fiddle