I'm trying to put an array inside an array (inside an array) using PHP.
$objectArray = array ('id' => $place, 'name'=>$placeName, array ('contact_info'=> array ('phone'=>$phone, 'email'=>$email,'website'=>$website)));
$data3 = array('place' => $objectArray);
$data_json = json_encode($data3);
echo $data_json;
This gives me something like this:
{
"place": {
"0": {
"contact_info": {
"phone": "513-555-1212",
"email": "jmr#example.com",
"website": "https://example.com"
}
},
"id": "999999",
"name": "My House",
}
}
What I'm looking for as an end product is:
{
"place": {
"contact_info": {
"phone": "513-555-1212",
"email": "jmr#example.com",
"website": "https://example.com"
},
"id": "999999",
"name": "My House",
}
I need to not have the '0' and the contact info part under place
For your purposes $objectArray should have this structure:
$objectArray = array (
'id' => $place,
'name'=>$placeName,
'contact_info'=> array ('phone'=>$phone, 'email'=>$email,'website'=>$website)
);
So, contact_info should be on the same level as id and name, without new array.
You need something like this
$objectArray = array (
'id' => '99999',
'name'=>'My House',
'contact_info' => array (
'phone'=>'513-555-1212',
'email'=>'jmr#example.com',
'website'=>'https://example.com'
)
);
$data3 = array('place' => $objectArray);
$data_json = json_encode($data3);
echo $data_json;
Remove the array part placed before 'contact_info' so they come at same level.
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 am using following code for making data coming from database as json format
public function employeeSearch()
{
$arrayOfEmployee = array();
$arrayToPush = array();
$arrayToJSON = array();
$new_item = $this->apicaller->sendRequest(array(
"controller" => "Employee",
"action" => "employeeSearch",
"searchCriteria" => "12345"
));
$arrayOfEmployee = json_decode($new_item,true);
foreach($arrayOfEmployee as $key => $employee)
{
$arrayToPush = array('data' => $employee['FullName'], 'value' => $employee['_id']['$oid']);
array_push($arrayToJSON, $arrayToPush);
}
echo json_encode($arrayToJSON);
}
The output is
[{"data":"Aasiya Rashid Khan","value":"5aa662b0d2ccda095400022f"},
{"data":"Sana Jeelani Khan","value":"5aa75d8fd2ccda0fa0006187"},
{"data":"Asad Hussain Khan","value":"5aaa51ead2ccda0860002692"},
{"data":"Ayesha Khan Khann","value":"5aab61b4d2ccda0bc400190f"},
{"data":"adhar card name","value":"5aaba0e1d2ccda0bc4001910"}
]
Now I want that json elements should look like
{
"suggestions": [
{
"value": "Guilherand-Granges",
"data": "750"
},
{
"value": "Paris 01",
"data": "750"
}
]
}
I have to implement this in jQuery autocomplete plugin...
Please help!!!
Replace the last line with
echo json_encode(["suggestions" => $arrayToJSON]);
This should result in the wanted result!
(This hold only true if you igonre the fact that the data in value and name is not the same/similar)
I am trying to convert this php array to a json. This is my code:
$c = array();
$c = array(
$c['cronjobs'] = array(
'id'=>1189515,
'groupId'=>12379,
),
);
$json = json_encode($c);
echo $json;
This is the output I'd like to acieve:
{"cronjobs":[{"id":1186437,"groupId":12379]}
Though using the above code this is what I am getting
[{"id":1189515,"groupId":12379}]
The [{"cronjobs"part is not appearing.
I'm not sure what I'm doing wrong.
This should get the result that you want (just wrap an array around the id, groupId array):
<?php
$c = array();
$c['cronjobs'] = array(array(
'id'=>1189515,
'groupId'=>12379,
));
echo json_encode($c);
// result {"cronjobs":[{"id":1189515,"groupId":12379}]}
?>
This is how you need to format your array:
$c = array(); // declare the array
$c['cronjobs'] = array( // populate the array
'id'=>1189515,
'groupId'=>12379,
);
$json = json_encode($c); // json_encode it
echo $json;
There is no need for $c = array($c['cronjob']); (which was what you were doing).
I think this is what you're looking for:
$c = array('cronjobs' => array());
$c['cronjobs'][] = array('id' => 1189515, 'groupId' => 12379);
//$c['cronjobs'][] = array('id' => 1234, 'groupId' => 4321);
$json = json_encode($c);
echo $json;
Cronjobs needs to contain an array of cronjob objects/arrays
Could also be written using one statement, like this:
$c = array('cronjobs' => array(
array('id' => 1189515, 'groupId' => 12379),
array('id' => 1234, 'groupId' => 4321)
));
Your problem is that in PHP array is used to represent both JSON objects and JSON lists hence the confusion. Consider the following code:
$cronjob = array(
'id' => 1189515,
'groupId' => 12379
);
echo json_encode($cronjob);
// {"id":1189515,"groupID":12379"}
As you can see this represents a single object. So we'll create a list of objects:
$cronjobs = array($cronjob);
echo json_encode($cronjobs);
// [{"id":1189515,"groupID":12379"}]
This is now a list as expected. Now the parent object:
$c = array(
'cronjobs' => $cronjobs
);
echo json_encode($c);
// {"cronjobs":[{"id":1189515,"groupID":12379"}]}
In JSON there is a name: value pair system
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "office",
"number": "646 555-4567"
}
],
"children": [],
"spouse": null
}
if you want to achieve like {"cronjobs":[{"id":1186437,"groupId":12379]} then the array must be named like the following in PHP:
$c['cronjobs'] = array(
'id'=>1189515,
'groupId'=>12379,
);
$json = json_encode($c);
echo $json;
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);
?>
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'];
}