Illegal string offset only when iterated as a set [duplicate] - php

This question already has answers here:
"Illegal offset" inside of loop [duplicate]
(2 answers)
PHP Warning - Illegal string offset
(1 answer)
Closed 1 year ago.
I know there are many other questions on this but my case is quite peculiar, my illegal offset only occurs when I iterate it with the others but is fine when I do it on its own.
I am using Slimframework.
My array looks like this:
{
"cart": {
"cartId": "9c7b7c3e-d4d3-4de1-afa4-f81e63b50906",
"orderNo": 1,
"orderType": "Collection",
"customerName": "",
"customerTel": "",
"address": "",
"items": [
{
"itemId": 2,
"itemName": "Item A",
"itemPrice": 5.75,
"qty": 1
},
{
"itemId": 1,
"itemName": "Item B",
"itemPrice": 5.25,
"qty": 1
},
{
"itemId": 4,
"itemName": "Item C",
"itemPrice": 9.3,
"qty": 1
},
{
"itemId": 3,
"itemName": "Item D",
"itemPrice": 8.6,
"qty": 1
}
]
},
"shopId": 1,
"discount": 0,
"total": "28.90",
"method": "Card"
}
When I do this in slimframework:
$order = $request->getParsedBody();
$this->response->withJson($order['cart']['items']);
It returns the exact same array moreover, if I check what is $order['cart']['items'][0]['itemPrice'] I get 5.75.
But when I iterate over it like:
foreach($order['cart']['items'] as $item)
{
$itemId = $item['itemId'];
$item = $item['itemName'];
$itemPrice = $item["itemPrice"];
$itemQty = $item["qty"];
}
I always get Illegal string offset 'itemPrice' & 'qty'.
I have also tried the below and it's not a problem:
$itemPrice;
foreach($order['cart']['items'] as $item)
{
$itemPrice .= $item["itemPrice"]
}
$this->response->withJson($itemPrice);
I might be missing something really obvious, any pointers would be highly appreciated.

You did override your loops $item variable with $item['itemName'];. From this point on your $item variable has no "itemPrice" nor "qty" keys, because it is scalar. You just need to change variable namings.
foreach($order['cart']['items'] as $item)
{
$itemId = $item['itemId'];
$item = $item['itemName']; /// <--- ! $item is no longer an item
$itemPrice = $item["itemPrice"];
$itemQty = $item["qty"];
}

Related

How to iterate arrays nested in arrays [duplicate]

This question already has an answer here:
Loop through nested arrays PHP
(1 answer)
Closed 12 months ago.
I have the json array below and im trying to access the ProductResults bit.
I want the output to be somthing like this:
Term: 47, Type:HP, Payment: 229.4
Term: 47, Type:PCP, Payment: 172.23
Term: 60, Type:PCP, Payment: 186.82
But im struggeling to even access other parts of the array.
PHP:
$json = json_decode($resp, true);
foreach ($json['VehicleResults'] as $item)
{
$data = $item['FinanceProductResults'];
$v0 = $data['Term'];
echo $v0;
}
JSON:
{
"VehicleResults": [{
"Id": "0",
"FinanceProductResults": [{
"Term": 47,
"AnnualMileage": 6000,
"Deposits": 1000,
"ProductResults": [{
"Key": "HP",
"Payment": 229.4
}, {
"Key": "PCP",
"Payment": 172.23
}]
}, {
"Term": 60,
"AnnualMileage": 6000,
"Deposits": 1000,
"ProductResults": [{
"Key": "HP",
"Payment": 186.82
}]
}]
}]
}
The FinanceProductResults is also an array so it needs to be accessed also as an array. Like you have accessed VehicleResults and same goes for ProductResults. So your code should look something like this.
$json = json_decode($resp, true);
foreach ($json['VehicleResults'] as $item)
{
$dataItems = $item['FinanceProductResults'];
foreach ($dataItems as $data) {
$v0 = $data['Term'];
foreach ($data['ProductResults'] as $productResult) {
$type = $productResult['Key'];
$payment = $productResult['Payment'];
echo "Term: $v0, Type: $type, Payment: $payment";
}
}
}

Looping through JSON using PHP [duplicate]

This question already has answers here:
PHP 7 array columns not working for multidimensional array
(1 answer)
How to extract and access data from JSON with PHP?
(1 answer)
Closed 2 years ago.
I have the below JSON I need to loop through in PHP.
{
"page": 1,
"perPage": 3,
"count": 607,
"status": "OK",
"tickers": [
{
"ticker": "A",
"name": "Agilent Technologies Inc.",
"market": "STOCKS",
"locale": "US",
"type": "CS",
"currency": "USD",
"active": true,
"primaryExch": "NYE",
"updated": "2020-12-15",
"codes": {
"cik": "0001090872",
"figiuid": "EQ0087231700001000",
"scfigi": "BBG001SCTQY4",
"cfigi": "BBG000C2V3D6",
"figi": "BBG000C2V3D6"
},
"url": ""
},
{
"ticker": "AA",
"name": "Alcoa Corporation",
"market": "STOCKS",
"locale": "US",
"type": "CS",
"currency": "USD",
"active": true,
"primaryExch": "NYE",
"updated": "2020-12-15",
"codes": {
"cik": "0001675149",
"figiuid": "EQ0000000045469815",
"scfigi": "BBG00B3T3HF1",
"cfigi": "BBG00B3T3HD3",
"figi": "BBG00B3T3HD3"
},
"url": ""
},
{
"ticker": "WADV",
"name": "Wireless Advantage Inc Common Stock",
"market": "STOCKS",
"locale": "US",
"type": "CS",
"currency": "USD",
"active": true,
"primaryExch": "GREY",
"updated": "2020-03-30",
"codes": {
"figiuid": "EQ0010295500001000",
"scfigi": "BBG001S87270",
"cfigi": "BBG000DKG4K2",
"figi": "BBG000DKG4K2"
},
"url": ""
}
]
}
This is my function to loop through - I simply only need the "ticker" from each of the nested arrays.
public function getTickers()
{
$APIKey = "API_KEY";
$tickers_request = 'API_URL';
$session = curl_init($tickers_request);
curl_setopt($session, CURLOPT_HEADER, true);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($session);
curl_close($session);
$json = substr($response, strpos($response, "{"));
$result = json_decode($json, true);
$ticker =[];
foreach($result as $results)
{
foreach ($results['tickers'] as $ticker)
{
$ticker['ticker'] = $results['ticker'];
}
}
return $ticker;
}
I receive these two errors in PHP -
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Severity: Notice
Message: Array to string conversion
What's wrong with my function? I'm a seasoned PHP developer but perhaps I am missing something...
Your code doesn't make sense. First you don't need the first foreach. All you need is
$result = json_decode($json, true);
$tickers =[];
foreach ($result['tickers'] as $results)
{
$tickers[] = $results['ticker'];
}
return $tickers;
Also your command $ticker['ticker'] doesn't make sense as it would store only 1 variable. I have changed it to $tickers[] = $results['ticker'] to store them in array. The result that way would look like:
array(3) {
[0]=>
string(1) "A"
[1]=>
string(2) "AA"
[2]=>
string(4) "WADV"
}
Your loop to extract the data isn't accessing the data at the right levels, you only need 1 loop which loops over the tickers array and then adds each ticker element to the new array (not sure what you were hoping the assignment was doing)...
foreach ($result['tickers'] as $res)
{
$ticker[] = $res['ticker'];
}

Search item on json object PHP [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
I have this kind of json objects and im trying to search an item under sales->products->id but i can't make it work. I hope someone could help me. Thanks!
"sales": [
{
"ID": 123456,
"transaction_id": "123456789",
"key": "sdawa57sd547sad4sadx54ad",
"subtotal": 20,
"tax": "0",
"fees": null,
"total": "20",
"gateway": "paypal",
"email": "email#email.com",
"date": "2018-08-01 13:13:55",
"discounts": null,
"products": [
{
"id": 1234,
"quantity": 1,
"name": "Product 1",
"price": 20,
"price_name": ""
}
]
}
This is the code i used:
$content = file_get_contents($url);
$results= json_decode($content, TRUE);
foreach($results->sales as $item)
{
if($item->products->id == "1234")
{
echo $item->products->name;
}
}
Because you've passed the second parameter as true to json_decode, your $results variable is an array, so you need to access it like that:
foreach($results['sales'] as $item) {
foreach ($item['products'] as $product) {
if ($product['id'] == '1234') echo $product['name'];
}
}
Output:
Product 1
Demo on 3v4l.org
If you want to find which sales have the product, then you should do this
$results= json_decode($content);
$productid = "1234"; //product you want to search for
foreach($result->sales as $sale)
{
$keys = array_keys(array_column($sale->products, 'id'), $product_id);
if(!empty($keys))
$saleIDs[] = $sale->ID;
}
var_dump($saleIDs); //contains all the sale IDs that have the product
Read about array_keys and array_column.

Store object into array and group all array with the same value in PHP

I'm working on array right now and I need to arrange this based on value.
{
"data": {
"id": 2,
"title": "second evaluation form",
"emp_position": "System Architecture",
"rating": 5,
"segments": [
{
"segment_name": "Job Role ",
"question": "How old are you?"
},
{
"segment_name": "360 Segments",
"question": "What is your food?"
},
{
"segment_name": "360 Segments",
"question": "sample question"
},
]
}
}
What I need to do is to store this object into array and group all question based on segment_name like this:
{
"data":[
{
"id": 2,
"title": "second evaluation form",
"emp_position": "System Architecture",
"rating": 5,
"segments": [
{
"segment_name": "Job Role "
"question_collection": [
{
"id": 4,
"question": "How old are you?"
}
]
},
{
"segment_name": "360 Segments",
"question_collection":[
{
"id": 1,
"question": "What is your food?"
},
{
"id": 2,
"question": "sample question"
}
]
},
]
}
]
}
And this is what I've tried to do:
$array_value =[];
foreach ($query AS $key => &$data) {
$array_value['id'] = $data['id'];
$array_value['title'] = $data['title'];
$array_value['emp_position'] = $data['position'];
$array_value['rating'] = $data['rating_count'];
if ( is_array($data) ) {
$array_value['segments'][$key]['segment_name'] = $data['segment'];
$array_value['segments'][$key]['question'] = $data['question'];
}
}
Collection function might help you find your solution.
$json = '{"data":{"id":2,"title":"second evaluation form","emp_position":"System Architecture","rating":5,"segments":[{"segment_name":"Job Role ","question":"How old are you?"},{"segment_name":"360 Segments","question":"What is your food?"},{"segment_name":"360 Segments","question":"sample question"}]}}';
$array = json_decode($json, true);
$coll = collect($array['data']['segments']);
$coll = $coll->groupBy('segment_name');
dump($coll);
Hope this helps you.Let me know if any problem
Do it like below:-
<?php
$json = '{
"data": {
"id": 2,
"title": "second evaluation form",
"emp_position": "System Architecture",
"rating": 5,
"segments": [
{
"segment_name": "Job Role ",
"id": 4,
"question": "How old are you?"
},
{
"segment_name": "360 Segments",
"id": 1,
"question": "What is your food?"
},
{
"segment_name": "360 Segments",
"id": 2,
"question": "sample question"
}
]
}
}
';
$query = json_decode($json,true);
$segment_array = [];
foreach($query['data']['segments'] as $arr){
$segment_array[$arr['segment_name']]['segment_name'] = $arr['segment_name'];
$segment_array[$arr['segment_name']]['question_collection'][] = ['id'=>$arr['id'],'question'=>$arr['question']] ;
}
$query['data']['segments'] = array_values($segment_array);
echo json_encode($query,JSON_PRETTY_PRINT);
OUTPUT:- https://eval.in/902194
Try this solution, You can loop by array and group all keys
$json = '{
"data": {
"id": 2,
"title": "second evaluation form",
"emp_position": "System Architecture",
"rating": 5,
"segments": [
{
"segment_name": "Job Role ",
"question": "How old are you?"
},
{
"segment_name": "360 Segments",
"question": "What is your food?"
},
{
"segment_name": "360 Segments",
"question": "sample question"
}
]
}
}';
$data = json_decode($json,true);
$segments = $data['data']['segments'];
$new_segemnts = array();
foreach($segments as $segemnt)
{
$key = $segemnt['segment_name'];
$new_segemnts[$key]['segment_name']=$segemnt['segment_name'];
$new_segemnts[$key]['question_collection'][]=array("question"=>$segemnt['question']);
}
$data['data']['segments'] = array_values($new_segemnts);
echo json_encode($data,JSON_PRETTY_PRINT);
DEMO
Here try my answer. I've just editted your existing code so you won't confuse that much. Nothing much to explain here. I included some explaination in my comment.
CODE
$array_value =[];
foreach ($query AS $key => &$data) {
$array_value['id'] = $data['id'];
$array_value['title'] = $data['title'];
$array_value['emp_position'] = $data['position'];
$array_value['rating'] = $data['rating_count'];
if ( is_array($data) ) {
// Check if segment is already added
$has_segment = false;
$segment_key = null;
foreach($array_value['segments'] as $key2 => $val){
//If segment is already added get the key
if($val['segment_name'] == $data['segment']){
$segment_key = $key2;
$has_segment = true;
break;
}
}
// if segment does not exists. create a new array for new segment
if(!$has_segment){
$array_value['segments'] = array();
}
// If new segment, get the index
$segment_key = count($array_value['segments']) - 1;
// If new segment, create segment and question collection array
if(!array_key_exists('question_collection', $array_value['segments'][$segment_key])){
$array_value['segments'][$segment_key]['segment_name'] = $data['segment'];
$array_value['segments'][$segment_key]['question_collection'] = array();
}
//Add the id for question collectiona rray
$array_value['segments'][$segment_key]['question_collection'][] = array(
"id" => $data['question_id'],
"question" => $data['question']
);
}
}

PHP Create Multidimension Array for JSON output

I feel terrible even asking because I have been TRYING to understand and comprehend other peoples examples this is what i'm TRYING to accomplish
{
"field": [
{
"appid": 0,
"page": 0,
"fieldname": "Sweet",
"value": "Tammy Howell"
},
{
"appid": 1,
"page": 1,
"fieldname": "Cecilia",
"value": "Shana Jordan"
},
{
"appid": 2,
"page": 2,
"fieldname": "Merritt",
"value": "Copeland Pena"
}
]
}
I need to be able to make the above JSON output happen when doing an SQL SELECT statement
Here is my currentCode
$x = 0;
$userFieldsResult = mysqli_query($database_id, "SELECT * FROM theDB.DynamicFields ORDER BY Page, Priority") or die (mysqli_error($database_id));
if (mysqli_num_rows($userFieldsResult)<=0)
{
echo "nothing found";
exit;
} else
{
while($row = mysqli_fetch_array($userFieldsResult))
{
$userFields[$x]['appid'] = $row['appid'];
$userFields[$x]['page'] = $row['page'];
$userFields[$x]['fieldname'] = $row['fieldname'];
$userFields[$x]['value'] = $row['value'];
$x++;
}
echo json_encode($userFields);
exit;
}
echo json_encode($userFields);
This is normally how i just been outputting json so they each are just part of 1 array looping, but I am trying to understand how to create more "in-depth" JSON arrays so they have a specific identifier before they list out the information.
[
{
"appid": 0,
"page": 0,
"fieldname": "Sweet",
"value": "Tammy Howell"
},
{
"appid": 1,
"page": 1,
"fieldname": "Cecilia",
"value": "Shana Jordan"
},
{
"appid": 2,
"page": 2,
"fieldname": "Merritt",
"value": "Copeland Pena"
}
]
In my example I just want to be able to have "field" be the "upper" part of the array that holds all the information as i showed in the example above.
You need to add field as parent array to your array.
Change from
echo json_encode($userFields);
Into
$json = array('fields' => $userFields);
echo json_encode($json);
In this particular configuration, you are being returned an object with properties, of which, the property's value may be an array.
So what you should actually be doing is creating a stdClass object in PHP and assigning it a property of "field" which is an empty array. Then you can push into this array stack.
$obj = new stdClass();
$obj->fields = array();
while(....){
$obj->fields[$x]['appid'] =
$obj->fields[$x]['appid'] = $row['appid'];
$obj->fields[$x]['page'] = $row['page'];
$obj->fields[$x]['fieldname'] = $row['fieldname'];
$obj->fields[$x]['value'] = $row['value'];
}
Now you can json encode the object and return it.
echo json_encode($obj);

Categories