I am receiving a JSON String, which has multiple unknown keys. It's pretty hard to explain, because those JSON strings are pretty large, I'll try to break them down in the most efficient way.
I use PHP to break down the object, that I get, when I decode the JSON string.
$data1 = $json->result->map->12313214654[0]
$data2 = $json->result->map->12313214654[2]
$differentdata1 = $json->result->map->12313214655[0]
As you can see, there are different subsections after the map key.
Those are numbers, that are pretty random. And their appearance isn't regular either. So sometimes there's just one subsection (or number), and sometimes more.
How can I access them? I tried to use $datacount = $count($json->result->map) But it always displays 1. And then I still wouldn't be able to access the subelements of the map key.
Does anyone have a solution for this?
As you seem to have an unknown amount of data in array form, you could iterate your results with a foreach loop:
foreach ($json->result->map as $key => $dataArray) {
// $key will be the numeric key, e.g. 12313214654
// $dataArray will be the array of data you're after
foreach ($value as $dataIndex => $data) {
// $dataIndex is the position of $data within the $dataArray
// $data is the value you were trying to access with $json->result->map->12313214654[n]
// You do your work with $data here.
print_r($data);
}
}
Related
I have general data array and I need to get array of specific data inside this general array so I can match it against my database.
Code
$nums = [];
foreach($request->phones as $phone) {
foreach($phone['_objectInstance']['phoneNumbers'] as $number) {
$nums = $number['value'];
}
}
$contacts = User::whereIn('phone', $nums)->get();
PS: $number['value'] is the data that I want to make array of it.
Sample data that I receive in backend
current error
Argument 1 passed to Illuminate\\Database\\Query\\Builder::cleanBindings() must be of the type array, string given, called in /home/....../vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php on line 918
exception: "TypeError"
Question
How can I make array of my numbers?
Ps: please if you know cleaner way to write this code, than my code above don't hesitate to share with me.
You're assigning $nums to be a new string on every iteration of the loop, rather than appending it to the array.
Just switch this line out:
$nums = $number['value'];
For
$nums[] = $number['value'];
Here are the docs for array_push(), which is the long way of writing the second line.
You are declaring $nums array, but inside the loop, you re-declaring it by a string again.
Fix the array assignments like that.
$nums[] = $number['value'];
Any idea on how to restructure the json below:
$jsonArray = [{"Level":"77.2023%","Product":"Milk","Temperature":"4"},
{"Level":"399.2023%","Product":"Coffee","Temperature":"34"},
{"Level":"109.2023%","Product":"Chocolate","Temperature":"14"}]
Expected outcome:
$expected = {"Milk":{"Level":"77.2023%","Temperature":"4"},
"Coffee":{"Level":"399.2023%","Temperature":"34"},
"Chocolate":{"Level":"109.2023%","Temperature":"14"}
}
I'm new and my thinking is get the product value in array and again use foreach loop to find the others value? .
Here's one possibility:
$jsonArray = '[{"Level":"77.2023%","Product":"Milk","Temperature":"4"},
{"Level":"399.2023%","Product":"Coffee","Temperature":"34"},
{"Level":"109.2023%","Product":"Chocolate","Temperature":"14"}]';
$output = array();
foreach (json_decode($jsonArray, true) as $row) {
$product = $row['Product'];
$output[$product] = $row;
unset($output[$product]['Product']);
}
echo json_encode($output);
Output:
{"Milk":{"Level":"77.2023%","Temperature":"4"},
"Coffee":{"Level":"399.2023%","Temperature":"34"},
"Chocolate":{"Level":"109.2023%","Temperature":"14"}
}
Demo on 3v4l.org
This made some trick
$a = '[{"Level":"77.2023%","Product":"Milk","Temperature":"4"},
{"Level":"399.2023%","Product":"Coffee","Temperature":"34"},
{"Level":"109.2023%","Product":"Chocolate","Temperature":"14"}]';
$newAr = array();
foreach(json_decode($a,true) as $key=>$value)
{
$newAr[$value['Product']] = array(
'Level' => $value['Level'],
'Temperature' => $value['Temperature'],
);
}
There are many ways to perform this with Loops in PHP. Other answers demonstrate it accurately. I would also suggest to integrate some form of Error handling, data validation/filtering/restriction in your code to avoid unexpected results down the road.
For instance, json_decode(), either assigned to a variable pre-foreach or straight in the foreach() 1st argument will just raise a warning if the original json is not valid-json, and just skip over the foreach used to construct your final goal. Then if you pass the result (that may have failed) directly to your next logic construct, it could create some iffy-behavior.
Also, on the concept of data-validation & filtering, you could restrict the foreach(), or any other looping mechanism, to check against a Product_List_Array[Milk,Coffee,Chocolate], using if(in_array() ...) so the final/goal object only contains the expected Products, this, in the case the original json has other artifacts. Filtering the values can also increase stability in restricting, for example, Temperature to Float.
I feel like i'm missing something quite simple. What are some of the best ways to iterate through combinations of $key names -- doing something different for each-- in a php foreach loop?
I have a number of values in an array with key values that follow the same naming format.
Example:
$rec_items['title3'] = implode($meta['title3']);
$rec_items['title4'] = implode($meta['title4']);
$rec_items['title5'] = implode($meta['title5']);
The $rec_items array also contains other values that do not follow this naming convention (or data type).
I'm looping through $rec_items with a foreach loop. I would like to be able to dynamically cycle through key names in $rec_items, and 'do something' when a key is found that matches title*. I've tried pushing numeric numbers from a counter variable into key names to be searched for (like below):
foreach ($rec_items as $key => $value){
$c = 0;
if(!empty($key[${'title'.$c}]){
$c++;
//do something
}
I believe that I cannot pass the value ${'title'.$c} into $key[] and have tried to pass the value of ${'title'.$c} as a string with no luck.
I just share the above to try to highlight what i'm trying to achieve.
(1) dynamically loop through key names in the format 'title*'
(2) if the key name is present in the $rec_items array ... do something.
I'm not sure what your original code was trying for; you appeared to be treating the array key like an array itself? Using a variable variable? Anyway, you just need a simple string search of the key. You can use regular expressions or whatever you like for more complex matching.
<?php
$rec_items = ["foo"=>12, "bar"=>34, "title1"=>56, "title2"=>78, "baz"=>90];
foreach ($rec_items as $k=>$v) {
if (strpos($k, "title") === 0) {
echo "$k = $v\n";
}
}
Output:
title1 = 56
title2 = 78
I am trying to retrieve user data from a SQL table where one of the columns is blob_medium. I run the SQL query properly and get the data in the php script.
if(mysqli_num_rows($result)){
while($row=mysqli_fetch_assoc($result)){
$result_array['user_data'][]=$row;
}
}
Now, to json_encode this data, I need to encode the data of user_pic column to base 64. For that I am trying this. But, it seems I am doing something wrong. Any kind of help would be appreciated.
foreach($result_array as $key){
foreach($key as $key2){
//print_r(base64_encode($key2['user_pic']).'<br/>'.'<br/>');
$key2['user_pic'] = base64_encode($key['user_pic']);
//print_r(($key['user_pic']).'<br/>'.'<br/>');
}
}
When I uncomment the print_r statements my data is printed in base64 format but the data of the assoc array is not changing.
That's because the array's $key and $keys in the for loop are copies. If you want them to modify the original you can either do it by specifying them to be references, not copies:
foreach($result_array['user_data'] as &$key){
$key['user_pic'] = base64_encode($key['user_pic']);
}
Or by explicit index into the original:
foreach($result_array['user_data'] as $index => $key){
$result_array['user_data'][$index] ['user_pic'] = base64_encode($key['user_pic']);
}
That's because you're changing the $key2 array. A temporary value created by your foreachloop. I myself would recommend using a for loop in this specific situation, because I was told to never use a loop within a loop if I can prevent it, and it makes things a lot easier to read:
for($i=0; $i < count($result_array['user_data']); $i++){
$encodedUserPic = base64_encode($result_array['user_data'][$i]['user_pic']);
$result_array['user_data'][$i]['user_pic'] = $encodedUserPic;
}
my returned json looks like this http://pastebin.com/Nbr161s3
I want to echo
body->airTicketListResponse->routings->mainAirlineName
body->airTicketListResponse->routings->adultBasePrice
body->airTicketListResponse->routings->trips->segments->departureAirportCode
body->airTicketListResponse->routings->trips->segments->departureTime //only the time here
body->airTicketListResponse->routings->trips->segments->duration
for each routings.
How do I do this? Here is what I have but I am lost and I know it is way off.
$result = data returned here http://pastebin.com/Nbr161s3
$airTicketListResponse = $result->body->airTicketListResponse;
$routings = $result->body->airTicketListResponse->routings;
$trips = $result->body->airTicketListResponse->routings->trips;
$segments = $result->body->airTicketListResponse->routings->trips->segments;
foreach($airTicketListResponse as $item){
$i=0;
$i<count($routings);
echo '<span style="font-weight:bold;">Airline - '.$item->routings[i]->mainAirlineName.' Price - '.$item->routings[i]->adultBasePrice.'</span><br />'.$item->routings[i]->trips[i]->segments[i]->departureAirportCode.' '.$item->routings[i]->trips[i]->segments[i]->departureTime.'<br /><br />';
$i++;
}
Please help if you can.
Before working with JSON you should be familiar with working with arrays and objects since JSON is nothing more than that.
It seems you already know these two concepts
To access an object property in PHP you use obj->property
To access a value of an array you specify the index inside brackets array[0]
With JSON you just have to keep in mind that some of your object properties will be arrays.
Now, since your data comes in a multi-level three-like structure you should also be familiar with traversing arrays, PHP offers an implementation of a foreach loop that is ideal for traversing dynamically generated arrays
using foreach($array as $index => $var) the $index and $var variables are automatically set to the index and value of each element in the array as they are being traversed, so you don't manually need to keep track of the index (i.e. $i)
Now let's start going through your data:
First we find your routings array
$result = json_decode($data);
$airTicketListResponse = $result->body->airTicketListResponse;
$routings = $airTicketListResponse->routings;
Now we use foreach to loop through every routing and print the needed properties
foreach($routings as $routing){ //$routing will hold the object value in each loop
echo 'Airline '.$routing->mainAirlineName.'<br>';
echo 'Adult Base Price '.$routing->adultBasePrice.'<br>';
}
Getting single properties like the above is pretty straight forward, but for the information of the segments we would first need a nested foreach since we have multiple trips for each routing and then a second nested foreach since each trip has multiple segments
foreach($routings as $routing){ //$routing will hold the object value in each loop
echo 'Airline '.$routing->mainAirlineName.'<br>';
echo 'Adult Base Price '.$routing->adultBasePrice.'<br>';
foreach($routing->trips as $trip){
foreach($trip->segments as $index => $segment){
echo 'Segment '.$index.':<br>'
echo 'Depart From '.$segment->departureAirportCode.'<br>';
echo 'Departure Time '.$segment->departureTime.'<br>';
echo 'Duration '.$segment->duration.'<br>';
}
}
}
And that would be it. I hope my explanation was clear and you got the idea of how to traverse JSON objects
If you feel more comfortable working with an array than with an object to access your data [which might be where you're getting confused here] then you can use json_decode with an additional argument:
$data = json_decode($result, true);
This will leave you with an array ($data) containing all your flight information, you can then var_dump() it and see the hierarchy you're dealing with and loop through it.