PHP array returning only 1 item - php

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

Related

Prepend key value to array - PHP

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

How to search an index by value in two dimensional array in php

I have a function to get description of courier , all records fetched about courier and are stored in $couriers . $courier is two dimensional array since it containing all rows of table couriers .
[
{
"id":"1",
"name":"DTDC",
"description":"Automatically inserted by application ",
"bloked":"false"
},
{
"id":"2",
"name":"Ecomm",
"description":"Nothing",
"bloked":"false"
},
{
"id":"3",
"name":"MarginPrice",
"description":"Local only",
"bloked":"false"
}
]
Now , i have to fetch decription of courier whose id is given . For
this purpose , i must know the index of the records .. I tried it
using array_search but "hard time" . So , i ask for help to give idea
to know the index of that records in array
function getCourierDescriptionById($id)
{ global $couriers;
if($couriers==null)
{
loadCourier($id);
}
$index=array_search($id,$couriers);// Here is the problem
return isset($couriers[$index]['description'])?
$couriers[$index]['description']:null;
}
Try this way easy to use
$j = '[
{
"id":"1",
"name":"DTDC",
"description":"Automatically inserted by application ",
"bloked":"false"
},
{
"id":"2",
"name":"Ecomm",
"description":"Nothing",
"bloked":"false"
},
{
"id":"3",
"name":"MarginPrice",
"description":"Local only",
"bloked":"false"
}
]';
$arr = json_decode($j,true);
$courier =array();
foreach($arr as $sample){
$courier[$sample['id']] = $sample;
}
//make sure your courier variable has id which you want to find "Its easy to search"
function getCourierDescriptionById($id)
{ global $courier;
return isset($courier[$id])? $courier[$id]:null;
}
print_r(getCourierDescriptionById(3));//function call which want to find
Your $courier variable has change for Easy to find, Which is contain array like that:
Array
(
[1] => Array
(
[id] => 1
[name] => DTDC
[description] => Automatically inserted by application
[bloked] => false
)
[2] => Array
(
[id] => 2
[name] => Ecomm
[description] => Nothing
[bloked] => false
)
[3] => Array
(
[id] => 3
[name] => MarginPrice
[description] => Local only
[bloked] => false
)
)
You $courier variable is not an array , it is a json string , so dcode it first which turns it to in php array.
$couriers = json_decode($couriers,true);
Now your function , can be defined as below , by using array_map
function getCourierDescriptionById($id)
{ global $couriers;
$args=func_num_args();
if($couriers==null)
{
loadCourier($id);
}
$index=array_search($id,array_map("getAllCourierId",$couriers));
return isset($couriers[$index]['description'])?
$couriers[$index]['description']:null;
}
Now the function who is bounded with array_map as below
function getAllCourierId($arr)
{
return $arr['id'];
}
Use this
$jsonArray = '[
{
"id":"1",
"name":"DTDC",
"description":"Automatically inserted by application ",
"bloked":"false"
},
{
"id":"2",
"name":"Ecomm",
"description":"Nothing",
"bloked":"false"
},
{
"id":"3",
"name":"MarginPrice",
"description":"Local only",
"bloked":"false"
}
]';
$arrData = json_decode($jsonArray,true);
print_r(searchForId('3',$arrData,'id'));
function searchForId($id, $array,$field) {
foreach ($array as $key => $val) {
if ($val[$field] === $id) {
return $val['description'];
}
}
return null;
}

creating nested associative array from json code

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

How to Decode Json object in laravel and apply foreach loop on that in laravel

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

How to get values from nested JSON data?

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'];
}

Categories