{
"books": [
{
"id": 2331,
"image": "http://lol.org/flower.png",
"images": [
{
"256x144": "http://lol.org/bee.png",
"650x320": "http://lol.org/fly.png"
}
],
....
I have json data like above but my problem is how to get out 650x320 data.
$data = json_decode($jsondata,true);
$gg = sizeof($data['books']);
for($x=0;$x<$gg;$x++){
Codes below works fine
$image = $data['books'][$x]['image'];
but how to fetch images on a second json level? I have tried code below with no luck.
$image = ($data->{'books'}->{'images'}->{'320x180'});
$image = $data['books']['images'][$x]['320x180'];
function getImageLinksFor($json, $dimension='650x320') {
$links = array();
$objJson = json_decode($json);
// GET THE MAIN BOOKS OBJECT...
$books = $objJson->books;
// LOOP THROUGH THE $books OBJECT AND PERFORM YOUR SEARCH FOR IMAGES
foreach ($books as $obj) {
// SINGLE OUT THE IMAGES OBJECT
$images = $obj->images;
// SINCE IT IS ALSO AN ARRAY, SIMPLY LOOP THROUGH IT AND FETCH THE DESIRED DIMENSION.
foreach ($images as $key => $objImgData) {
if(property_exists($objImgData, $dimension)){
$links[] = $objImgData->$dimension;
}
}
}
if(count($links) == 1){
return implode("", $links);
}
return $links;
}
var_dump(getImageLinksFor($json, '650x320'));
'books' is an Array of objects, you will need to select an object using a numeric index.
$image = $data['books'][$insertIndexHere]['images'][$insertIndexHere]['320x180'];
Essentially you have missed the [$x] between 'books' and 'images' from your first code which works.
You will probably want a loop which iterates through each book and then a second nested loop which iterates through the images in each book.
For example:
$gg = sizeof($data['books']);
for($x=0;$x<$gg;$x++) {
$images = data['books'][$x]['images'];
$sizeOfImages = sizeof($images);
for($j = 0; $j < $sizeOfImages; $j++) {
// access $images[$j]['320x180']
}
}
Related
This is the part where json gets decoded
$response = file_get_contents("download.json");
$json = json_decode($response, true);
Example of data
{"count":2948,"errors":"","offers":[{"id":"85305","name":"Some Name",
Each of the offers has name
The data goes like this json->offers->name
How to remove all otheroffers if name has been mached with another offer?
And leave only one offer with the same name?
lazy solution:
$arrayFromJson = (json_decode($json));
$offers = [];
$customers = [];
foreach ($arrayFromJson->toppings as $value) {
if(in_array($value->name, $customers)){
continue;
}
$offers[] = $value;
$customers[] = $value->name;
}
$arrayFromJson->toppings = $offers;
let's suppose that the json response file has the following values:
$response = '{"count":2948,"errors":"","offers":[{"id":"1","name":"a"},{"id":"2","name":"b"},{"id":"3","name":"c"},{"id":"4","name":"a"},{"id":"5","name":"c"},{"id":"4","name":"a"},{"id":"4","name":"a"},{"id":"4","name":"b"}]}';
decode them:
$json = json_decode($response, true);
then remove the repeated offers:
// make sure that the required index is exists
if(!empty($json['offers'])){
$json = scan_json_array($json['offers']);
}
by the following recursive function:
function scan_json_array(array $arr, $index = 0){
// if we reached the last element of the array, exit!
if($index == (sizeof($arr)-1)){
return $arr;
}
for(; $index<sizeof($arr);){
$current = $arr[$index];
for($j=$index+1; $j<sizeof($arr); $j++){
$next = $arr[$j];
if($current['name'] === $next['name']){
// remove the matched element
unset($arr[$j]);
// re-index the array
$arr = array_values($arr);
// if it was the last element, increment $index to move forward to the next array element
if($j == (sizeof($arr)-1)){
$index++;
}
return scan_json_array($arr, $index);
}
}
$index++;
}
}
I am parsing thorugh a eBay API response. I want to deliver this back to a website cleaner and easier to parse with JavaScript. I successfuly Parsed through the XML... but now turning that into JSON to resend back to the client is giving me some headaches.
NOTE: $resp is the response from eBay. It's their full length XML that is successfully parsed with the code below.
For example... $valueName could be Grade. And then I go into the next foreach loop and get the values for this. These values may be 10, 9.5, 9 etc.
Here is my PHP code.
$arrayName = array();
$arrayValue = array();
foreach($resp->aspectHistogramContainer->aspect as $name) {
$nameAspect = $name['name'];
//$arrayName["aspectName"] = $nameAspect;
foreach($name->valueHistogram as $value) {
$valueAspect = $value['valueName'];
//$arrayValue["aspectValue"] = $valueAspect;
}
//array_push($arrayName, $arrayValue);
}
echo json_encode($arrayName);
So, without me trying to create my own JSON, I am getting that I need. I echos results and it was similar to this...
NAME
----- Value
----- Value
----- Value
NAME
----- Value
NAME
etc etc
For a JSON response... Im looking for something like...
[
{
"name": "NAME",
"value": ["value", "value"]
}, {
"name": "name",
"value": ["value", "value"]
}
]
Any help and guidance would be greatly appreciated.
eBay's response is like this (there are A LOT more <aspect> and <valueHistogram>)
<getHistogramsResponse xmlns="http://www.ebay.com/marketplace/search/v1/services">
<ack>Success</ack>
<version>1.13.0</version>
<timestamp>2018-11-07T15:32:20.380Z</timestamp>
<aspectHistogramContainer>
<domainDisplayName>Baseball Cards</domainDisplayName>
<aspect name="Card Manufacturer">
<valueHistogram valueName="Ace Authentic">
<count>19</count>
</valueHistogram>
<valueHistogram valueName="American Caramel">
<count>2024</count>
</valueHistogram>
<valueHistogram valueName="APBA">
<count>10554</count>
</valueHistogram>
<valueHistogram valueName="Bazooka">
<count>8826</count>
</valueHistogram>
<valueHistogram valueName="Be A Player">
<count>17</count>
</valueHistogram>
<valueHistogram valueName="Bell Brand Dodgers">
<count>334</count>
To encode it (and assuming SimpleXML), then it's just a case of building each internal $aspect data array and then adding the values to it. I use (string) to ensure the data is not stored as a SimpleXMLElement, which can cause side effects...
$arrayName = array();
foreach($resp->aspectHistogramContainer->aspect as $name) {
$aspect = [ "name" => (string)$name['name']];
foreach($name->valueHistogram as $value) {
$aspect["value"][] = (string)$value['valueName'];
}
$arrayName[] = $aspect;
}
echo json_encode($arrayName);
with the sample XML, this gives...
[{"name":"Card Manufacturer","value":["Ace Authentic","American Caramel","APBA","Bazooka","Be A Player","Bell Brand Dodgers"]}]
Create one single array $resultArray and store values in it. By maintaining your current code structure with minimal changes, here is the updated code snippet,
$resultArray = array();
$i = 0; // Maintain Array Index value
foreach($resp->aspectHistogramContainer->aspect as $name) {
$resultArray[$i]["aspectName"] = (string)$name['name'];;
foreach($name->valueHistogram as $value) {
$resultArray[$i]["aspectValue"][] = (string)$value['valueName'];
}
$i++; // Increment array index to store next value
}
echo json_encode($resultArray);
$results = array();
// Parse the XML into a keyed array
foreach($resp->aspectHistogramContainer->aspect as $name) {
$nameAspect = (string) $name['name'];
$values = array();
foreach($name->valueHistogram as $value) {
$values[] = (string) $value['valueName'];
}
$results[$nameAspect] = $values;
}
// This keeps things simple - rewrite to the required JSON format
$outputForJSON = array();
foreach ($results as $name => $values) {
$outputForJSON[] = array(
"name" => $name,
"values" => $values
);
}
echo json_encode($outputForJSON);
$session_activity_category = array();
foreach($search_venue as $venue_b) {
$session_activity_category[] = $this->users_model->search_categories_by_session($venue_b->activity_venue_id);
}
return $this->output
->set_content_type('application/json')
->set_status_header(200)
->set_output(json_encode(array('activity_category'=>$session_activity_category,'activity'=>$session_activity,'activity_session'=>$search_session,'activity_venue'=>$search_venue),JSON_UNESCAPED_SLASHES)
);
I want to remove the arrays given in the arrow lines
Convert the JSON to the array. Then just create a new array with the same key active category (in my example, something):
<?php
$json = '
{"something": [[
{
"blah": "blah"
},
{
"blah": "blah"
}
]]}
';
$array = json_decode($json, true);
$array = [
"something" => $array['something'][0],
];
echo json_encode($array);
Which will output:
{"something":[{"blah":"blah"},{"blah":"blah"}]}
Seems that $this->users_model->search_categories_by_session($venue_b->activity_venue_id) returns array of objects. You should parse this objects to the $session_activity_category array each iteration of search_categories_by_session function call.
$session_activity_category = array();
array_walk($search_venue, function($venue_b) use (&$session_activity_category) {
$categories = $this->users_model->search_categories_by_session($venue_b->activity_venue_id);
foreach ($categories as $category) {
$session_activity_category[] = $category;
}
});
I am trying to loop through a JSON Array returning a unique date and all the tasks associated with that date.
This is an example of my JSON array:
<!-- language: lang-json -->
[
{
"task":"Clean my teeth",
"date":"today"
},
{
"task":"Jumping Jacks",
"date":"tomorrow"
},
{
"task":"Call Mom",
"date":"today"
},
{
"task":"Wash The Dog",
"date":"2017/03/01"
},
{
"task":"Clean The House",
"date":"today"
}
]
I want to display something like this:
Today
Clean my teeth
Call Mom
Tomorrow
Jumping Jacks
2017/03/01
Clean The House
Here is my function: I can get all the unique days but I'm not sure how to display the tasks associated with that day.
public static function Iteration()
{
$file = file_get_contents("newfile.php");
$result = rtrim( $file, ",");
$array = json_decode('[' . $result . ']');
$unique_dates = array();
$unique_tasks = array();
foreach($array as $item) {
if ( in_array($item->date, $unique_dates) ) {
continue;
}
$unique_dates[] = $item->date;
$time = strtotime($item->date);
$newformat = date('Y-m-d',$time);
echo '<h2>' . $newformat . '</h2>';
echo $item->task;
}
}
You can traverse the JSON list, and keep the unique records and store tasks at the same traversal.
By using the isset(), you can determine whether the key is unique or not.
Try this:
<?php
$json = '[{"task": "Clean my teeth","date": "today"},{"task": "Jumping Jacks","date": "tomorrow"},{"task": "Call Mom","date": "today"},{"task": "Wash The Dog","date": "2017/03/01"},{"task": "Clean The House","date": "today"}]';
$array = json_decode($json);
$res = array();
foreach ($array as $each) {
if (isset($res[$each->date]))
array_push($res[$each->date], $each->task);
else
$res[$each->date] = array($each->task);
}
foreach ($res as $date => $tasks){
echo "<h3>{$date}</h3>";
foreach ($tasks as $task)
echo "<p>$task</p>";
}
I have a multidimensional PHP array looking like this in JSON:
array = [{
"id":"1",
"key":"Ferrari",
"type":"car"},
{
"id":"1",
"key":"Red",
"type":"color"},
{
"id":"73",
"key":"Yellow",
"type":"color"
}]
Because it's actually a search result, I would like to, dynamically combine the results where the id's are the same. In other words the new array should look like:
array = [{
"id":"1",
"key":"Red Ferrari",
"type":"keyword"},
{
"id":"73",
"key":"Yellow",
"type":"color"
}]
I have been looking at a lot of PHP functions, but they have a limited functionality, in multidimensional arrays. Any suggestions are appreciated :)
Many Regards
Andreas
There's no base functions to do as specific thing as you mention. So you can make something like this:
print_r(my_array_merge($data));
function my_array_merge($data)
{
// sort all records by id to merge them later
$data_by_id = array();
foreach ($data as $item)
{
if (!isset($data_by_id[ $item['id'] ])) {
$data_by_id[ $item['id'] ] = array();
}
$data_by_id[ $item['id'] ][] = $item;
}
// merge records with same id
$return = array();
foreach ($data_by_id as $id => $items)
{
foreach ($items as $item)
{
if (!isset($return[ $id ])) {
$return[ $id ] = $item;
} else {
$return[ $id ]['key'] .= ' ' . $item['key'];
$return[ $id ]['type'] = 'keyword'; // I don't really get what you mean by 'keyword'
}
}
}
// reset keys before return
return array_values($return);
}