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];
Related
Trying to read a json file and assign values to php variables.
My json file looks like this:
{
"123456": {
"fuelpump": {
"name": "Pump XX",
"address": "Address here",
"8493024" <-- I WANT THIS THE VALUE 8493024: {
"connectors": {
"8493024-1": {
"infohere": "more info here"
}
}
}
}
},
"456789": {
"fuelpump": {
"name": "Pump YY",
"address": "Address here",
"8374769" <-- I WANT THIS THE VALUE 8374769: {
"connectors": {
"8374769-1": {
"infohere": "more info here"
}
}
}
}
}
}
This is how my php code is looking:
<?php
$jsonfile = file_get_contents('jsonfile.json');
$jsonitems = json_decode($jsonfile);
foreach ($jsonitems as $location) {
$name = $location->fuelpump->name; //This works OK
$address = $location->fuelpump->address; // This ALSO OK
$fuelPumpno = $location->fuelpump[2]; //This doesnt work. Here i want the key names 8493024 and 8374769
}
How can i get the name of the keys "8493024" and "8374769"?
You have to loop over the fuelpump properties to find the value.
If that is the structure of the json object, and it does not change, you can do with this:
foreach ($location->fuelpump as $key => $value) {
if ($key !== 'name' && $key !== 'address') {
$fuelPumpno = $key;
}
}
Another way
it filters the keys of the $location object and get the first element of the result:
$fuelPumpno = current(array_filter(array_keys(get_object_vars($location->fuelpump)), function($el) {
return $el !== 'name' && $el !== 'address';
}));
Another approach is to filter only numeric values:
$jsonfile = file_get_contents('jsonfile.json');
$jsonitems = json_decode($jsonfile, true);
$pumpNo = [];
foreach ($jsonitems as $data) {
$pumpNo = array_merge($pumpNo, array_filter(array_keys($data["fuelpump"]), 'is_numeric'));
}
print_r($pumpNo);
It returns
Array
(
[0] => 8493024
[1] => 8374769
)
Im studying in array, and I was wondering How can I add key to this kind of array?
{
"items":[
{
"count":"1",
"id":123,
"description":"Bag",
"price":11
},
{
"count":1,
"id":1234,
"description":"10% Discount",
"price":-1.1
}
],
"total":9.9,
"discount_total":9.9
}
because I needed convert the array to have a key base on the id inside the array.
{
"items":{
"123":{
"count":"1",
"cart_id":123,
"description":"Bag",
"price":11
},
"1234":{
"count":1,
"cart_id":1234,
"description":"10% Discount",
"price":-1.1
}
},
"total":9.9,
"discount_total":9.9
}
and this is my code
header('Content-Type: application/json');
$cart_array = json_decode('{
"items":[
{
"count":"1",
"cart_id":123,
"plu":"TP16",
"description":"Bag"
},
{
"count":1,
"cart_id":1234,
"plu":"DISCT10",
"description":"10% Discount"
}
],
"total":9.9,
"discount_total":9.9
}');
foreach ($cart_array->items as $item)
{
$construct["cart_id"] = $item->cart_id;
}
I wanted to ask how can I put the id in the array? I cant use $cart_array['id'] = $value, it returns error.
Uncaught Error: Cannot use object of type stdClass as array
I could really use some explanation here
Following code can help you.
<?php
$json = '{
"items":[
{
"count":"1",
"cart_id":123,
"plu":"TP16",
"description":"Small Four Seasons"
},
{
"count":1,
"cart_id":1234,
"plu":"DISCT10",
"description":"10% Discount"
}
],
"total":9.9,
"discount_total":9.9
}';
$data = json_decode($json,TRUE); //json decode
foreach ($data['items'] as $key => $value)
{
$data['items'][$value['cart_id']] = $value;
unset($data['items'][$key]);
}
echo "<pre>";print_r($data);die;
?>
You don't have to loop at all. You can use array_column to make an array associative with one line of code.
$cart_array['items'] = array_column($cart_array['items'], NULL, 'cart_id');
https://3v4l.org/cPD5n
You can use this code in your application to add keys to indexed array.
foreach($obj as $key=>$val){
foreach ($val as $index=>$content){
$data[$content['id']]=$content;
}
}
You can get same output json data as per you want :
$array = json_decode($data,true);
if(isset($array['items']) && count($array['items']) > 0){
foreach($array['items'] as $key => $value){
$value['cart_id'] = $value['id'];
unset($value['id']);
$array['items'][$value['cart_id']] = $value;
unset($array['items'][$key]);
}
}
echo "<pre>";print_r($array);
echo json_encode($array);
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 some data on a MySQL database representing a tree structure, and I want to convert it into JSON. I have used a recursive function to read all the data but I have no idea on how to convert into an array.
Here is the recursive function:
public function buildTree($parent, $level) {
// retrieve all children of $parent
$results = Department::all()->where('parent_id',$parent);
// display each child
foreach($results as $result)
{
echo $this->buildTree($result['id'], $level+1);
}
}
And the following is the JSON result I'd like to have in the end:
[
{
"id":1,
"text":"Root node",
"children":[
{
"id":2,
"text":"Child node 1",
"children":[
{
"id":4,
"text":"hello world",
"children":[{"id":5,"text":"hello world2"}]
}
]
},
{
"id":3,
"text":"Child node 2"
}
]
}
]
Here is the sample data
public function buildTree($parent, $level) {
// The array which will be converted to JSON at the end.
$json_return = array();
// Get the current element's data.
$results = Department::all()->where('id',$parent);
$json_return['id'] = $parent;
$json_return['text'] = $results[0]['text']; // Or however you access the "text" parameter of the end JSON from the database.
// Retrieve all children of $parent
$results = Department::all()->where('parent_id',$parent);
if (count($results) > 0)
{
$json_return['children'] = array();
foreach($results as $result)
{
$json_return['children'][] = $this->buildTree($result['id'], $level+1);
}
}
// Going to assume that $level by default is 0
if ($level == 0)
{
echo json_encode(array($json_return));
}
return $json_return;
}
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);
}