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.
Related
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 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);
?>
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
Here's my JSON code:
{
"query": {
"count": 2,
"created": "2013-04-03T09:47:03Z",
"lang": "en-US",
"results": {
"yctCategories": {
"yctCategory": {
"score": "0.504762",
"content": "Computing"
}
},
"entities": {
"entity": [
{
"score": "0.902",
"text": {
"end": "19",
"endchar": "19",
"start": "0",
"startchar": "0",
"content": "Computer programming"
},
"wiki_url": "http://en.wikipedia.com/wiki/Computer_programming"
},
{
"score": "0.575",
"text": {
"end": "51",
"endchar": "51",
"start": "41",
"startchar": "41",
"content": "programming"
}
}
]
}
}
}
}
and below is my PHP code
$json_o = json_decode($json,true);
echo "Json result:</br>";
echo $json; // json
echo "</br></br>";
echo "Value result:</br>";
$result = array();
//$entity = $json_o['query']['results']['entities']['entity'];
foreach ($json_o['query']['results']['entities']['entity'] as $theentity)
foreach ($theentity['text'] as $thetext){
$result[] = $thetext['content'];
}
print_r($result);
My expectation is to get the value of content in entity, which is "Computer programming" and "programming".
I already searching around, but still have found the solution yet.
The result of my PHP code is:
Array ( [0] => 1 [1] => 1 [2] => 0 [3] => 0 [4] => C [5] => 5 [6] => 5 [7] => 4 [8] => 4 [9] => p )
Use this loop
foreach ($json_o['query']['results']['entities']['entity'] as $theentity)
{
$result[] = $theentity['text']['content'];
}
http://codepad.viper-7.com/tFxh1w
Output Array ( [0] => Computer programming [1] => programming )
Change your foreach to:
$result = array();
foreach ($json_o['query']['results']['entities']['entity'] as $theentity) {
$result[] = $theentity['text']['content'];
}
print_r($result);
$theentity['text'] is an array of keys => value. You can just access key content instead of looping through all of the entries.
Another way you could do it (though it is a poor choice) is:
foreach($theentity['text'] as $key => $value) {
if( 'content' === $key ) {
$result[] = $value;
}
}
I provide this second example to demonstrate why the original code did not work.
Update
To access other properties like the yctCategories just do something similar
$categories = array();
foreach ($json_o['query']['results']['yctCategories'] as $yctCategory) {
$categories[] = $yctCategory['content'];
}
print_r($categories);
remove the second foreach and replace it with $result[] = $theentity['text']['content'];
using something like http://jsonlint.com/ might make it easier for you to see how the json is structured. alternatively just var_dump (or print_r) the output of your json_decode.
Use simple code:
$array = $json_o['query']['results']['entities']['entity'];
foreach($array as $v){
echo $v['text']['content'];
}
I have a simple value pair array like this :
array(4) (
[4] => (string) Barcelona
[3] => (string) Cordoba
[1] => (string) Granada
[2] => (string) Jaen
)
I need to encode this to JSON to respond to an AJAX request in the following format :
[{"pk": 4, "name": "Barcelona"},
{"pk": 3, "name": "Cordoba"},
{"pk": 1, "name": "Granada"},
{"pk": 2, "name": "Jaen"}]
If I use :
json_encode($a)
I get the following :
{"4":"Barcelona","3":"Cordoba","1":"Granada","2":"Jaen","0":"Select a province"}
How do I get PHP to format my simple array to include properties in the JSON?
Just create a new array:
$data = array();
foreach($array as $key => $value) {
$data[] = array('pk' => $key, 'name' => $value);
}
$json = json_encode($data);