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);
}
Related
I am having trouble getting the name of a dynamic key from a JSON string.
I am using PHP
This is a sample of the JSON
{
"_text": "this is a test",
"entities": {
"dynamic_key": [
{
"confidence": 0.99,
"value": "thi is the answer"
}
]
},
"msg_id": "1234532123"
}
I am using foreach to go trough the json key and get the values
foreach ($json as $obj) {
$search_term = $obj->_text;
$msg_id = $obj->msg_id;
}
But I am not sure how to get the value of the "dynamic_key" which changes every time, and because of that I also cannot get the values of "confidence and value" keys.
Any ideas on how to approach this?
Followed #Dimi, solution. This is what I ended up with
$data=json_decode($json,true);
foreach ($data['entities'] as $key=>$val)
{
echo "Entity: $key";
foreach ($data['entities'] as $keys){
$conf = $keys[0]['confidence'];
$answer = $keys[0]['value'];
echo "conf: $conf, answ: $answer";
}
}
Can you provide a couple more examples?
Or try this code and let us know if it breaks
<?php
$json='{
"_text": "this is a test",
"entities": {
"dynamic_key": [
{
"confidence": 0.99,
"value": "thi is the answer"
}
]
},
"msg_id": "1234532123"
}';
$data=json_decode($json,true);
foreach ($data['entities'] as $key=>$val)
{
echo "VALUE IS $key\n values are ";
var_dump($val);
}
Using the data you've shown, there doesn't seem to be an array for the starting JSON.
But with that data the following will use foreach to both fetch the key and the data and then another sub-loop to fetch the confidencevalue...
$search_term = $json->_text;
$msg_id = $json->msg_id;
foreach ( $json->entities as $key => $entities ) {
echo $key.PHP_EOL;
foreach ( $entities as $entity) {
echo $entity->confidence.PHP_EOL;
}
}
If you decode the JSON as an array and if the dynamic key is the only key under entities, then:
$array = json_decode($json, true);
$dynamic = current($array['entities']);
$confidence = $dynamic['confidence'];
$value = $dynamic['value'];
Or shorter:
$confidence = current($array['entities'])['confidence'];
You can probably use reset, current and maybe array_pop etc.
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>";
}
{
"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']
}
}
I am trying to handle a situation with a nested multiple array that is received in PHP by $_POST from Javascript-Jquery (as Object not as Json)
. The nested Object looks like this:
{
"Videotheck":{
{
"Category":"Comedy",
"Title_Liste":[
{
"Title":"Millers",
"Year":"2014"
},
{
"Title":"Yogi",
"Year":"2012"
}
]
},
{
"Category":"Action",
"Title_Liste":[
{
"Title":"Rodulf",
"Year":"2014"
},
{
"Title":"Matrix",
"Year":"2000"
}
]
}
}
}
And now the information in this Object need to be splited. For example the title list of each category should be stored in a var
$comedy_title_liste = [];
$action_title_liste = [];
I tryed this:
if($_POST){
$arr1 = $_POST['Videotheck'];
foreach($arr1 as $vtk){
foreach($vtk as $data => $v){
foreach($v as $key => $value){
foreach($value as $k => $info){
echo $k.' '. $info;
}
}
}
}
}
Like this I can get only all title list from all categories, but is necessary to get for each category the list of titles separeted. I don't know really how to handle the situation.
Well this is what I have. I guest that there is something not correct.
Not 100% exact but you can give a try :
$result = array();
$parent = $_POST['Videotheck'];
foreach($parent as $key=> $child) {
$result[$child['Category']."_title_liste"] = array();
foreach($child['Title_Liste'] as $cKey => $val) {
$result[$child['Category']."_title_liste"][] = $val['Title'];
}
}
I have this
{
"items":[
{
"id":463282624,
"original_id":463282624,
"defindex":10175,
"level":1,
"quality":4,
"inventory":2147483980,
"quantity":1,
"attributes":[
{
"defindex":187,
"value":1106771968,
"float_value":31
}
]
},
{
"id":465686099,
"original_id":465686099,
"defindex":10175,
"level":1,
"quality":4,
"inventory":2147483979,
"quantity":1,
"attributes":[
{
"defindex":187,
"value":1106771968,
"float_value":31
}
]
}
]
}
How can i take out the ['id'] of the item with ['defindex'] = 10175
Please help!
PHP doesn't provide any way to retrieve elements by the contents, so you have to write a loop:
foreach ($object['items'] as $item) {
if ($item['defindex'] == 10175) {
$id = $item['id'];
break;
}
}
If you're going to need to do this repeatedly, you should transform your data into an associative array that uses defindex as the key, then you can access them easily.
$items_by_defindex = array();
foreach ($object['items'] as $item) {
$items_by_defindex[$item['defindex']] = $item;
}
$id = $items_by_defindex[10175];