Accessing array inside array - php

I'm working on my task right now, which accessing specific array when it is called by front end.
My example data is like this
{
"data": [
{
"name": "Jon Snow",
"id": "01-0001",
},
{
"name": "Robert Stark",
"id": "01-0002"
},
{
"name": "Sansa Stark",
"id": "01-002333"
},
{
"name": "Arya Stark",
"id": "01-00012"
},
{
"name": "Bran Stark",
"id": "01-0003"
},
{
"name": "Rickon Stark",
"id": "01-0005"
}
]
}
* In my front end I have this code *
selectedEmployee: any=null;
setActiveEmployee(employee: any) {
this.selectedEmployee = employee;
let myJSON = JSON.stringify(this.selectedEmployee);
this.perEmpLateEarly();
}
Whenever I choose the employee i get the id of that employee.
So in this, if i choose "id": "01-0001" it will return the first array and it will keep the rest, and if I choose "id": "01-0002" it will return the second one and will keep the rest and so on. How can I do that in Php?
Thanks in advance

You will do a GET/POST HTTP request from frontend, which would look something like this in
your_backend_page.php?id=<ID HERE>
Then the "your_backend_page.php" would look like as follows:
$list = { "data": [ { .... }, { ... }] } // this is the array you have
$idFromFrontEnd = $_GET["id"];
foreach ($list["data"] as $item) { // iterate over all items
if ($item["id"] == $idFromFrontEnd) { // check if id matches
echo json_decode($item); // if matches, print this item
}
}
Please note this approach is okay if you have a small number of items. For a larger list, you might want to have a database, where you can use sql to select.

Related

PHP get JSON key value from specific object

Ive got the following JSON:
{
"servers": [
{
"id": "f34c0185-4c9e-40fd-82f6-1d6e9a5d499e",
"name": "vm01"
},
{
"id": "d671ac7d-3b5a-4777-8510-6e8e58295061",
"name": "vm02"
},
{
"id": "h59j23cc-9ve2-4508-1277-85y1lo27562m",
"name": "vm03"
}
]
}
I also have another JSON that gives me the ID I want to search for.
For example: "d671ac7d-3b5a-4777-8510-6e8e58295061".
I want to search for the JSON Object, that contains that ID and get the value of the name key. I tried with loops and if, else's but I didn't manage to get it working.
Thanks for your help!
decode the json as array object then loop through with the ID that u want to search
<?php
$json = '{
"servers": [
{
"id": "f34c0185-4c9e-40fd-82f6-1d6e9a5d499e",
"name": "vm01"
},
{
"id": "d671ac7d-3b5a-4777-8510-6e8e58295061",
"name": "vm02"
},
{
"id": "h59j23cc-9ve2-4508-1277-85y1lo27562m",
"name": "vm03"
}
]
}';
$j = json_decode($json, true);
foreach($j['servers'] as $arr)
{
if( $arr['id'] == 'd671ac7d-3b5a-4777-8510-6e8e58295061' ) echo $arr['name'];
}
demo: https://3v4l.org/0DboX

PHP merge two arrays with same key and output to specific json format

My database has two tables. One is calling out the book info and another is calling image info. I would like to merge these two table data into one JSON. If the img id is matched with the data id, then the image is belongs to this book. I tried to use foreach to loop the book data into array and use another foreach to loop the image data within the book data array, but failed to get the expected result.
Book Table JSON:
{
"data": [
{
"id": 17,
"author": "Belcurls",
"bookname": "You Never Know"
},
{
"id": 18,
"author": "Carolina",
"bookname": "A Story Teller"
},
{
"id": 19,
"author": "Lokas",
"bookname": "The Love"
}
]
}
Image Table JSON:
{
"img": [
{
"id": 18,
"url": "image18.png"
},
{
"id": 18,
"url": "image18b.png"
},
{
"id": 19,
"url": "image19.png"
},
{
"id": 19,
"url": "image19b.png"
},
{
"id": 19,
"url": "image19c.png"
}
]
}
Expected Result:
{
"data": [
{
"id": 17,
"author": "Belcurls",
"bookname": "You Never Know"
},
{
"id": 18,
"author": "Carolina",
"bookname": "A Story Teller",
"image":[
{
"url":"image18"
},
{
"url":"image18b"
}
]
},
{
"id": 19,
"author": "Lokas",
"bookname": "The Love",
"image":[
{
"url":"image19"
},
{
"url":"image19b"
},
{
"url":"image19c"
}
]
}
]
}
Demo Link.
You can do this loop, Please check inline doc for explanation
foreach ($arr['data'] as $key => &$value) { // & to update changes as its address
foreach ($imgs['img'] as $key1 => $value1) {
if($value['id'] == $value1['id']){ // checking if match id of parent with images
$value['image'][] = ['url' => $value1['url']]; // then simply push
}
}
}
If you want to convert your json to php array use
json_decode($yourjson, true); // second parameter is for converting it to array else it will convert into object.
If you make the data array associative then you only need to loop the image array and add them to the correct subarray in data.
// This flattens the array and makes it associative
$data = array_column($data['data'], null, 'id');
foreach($img['img'] as $v){
$data[$v['id']]['image'][] = ['url' => $v['url']];
}
// Add the 'data' again
$final['data'] = array_values($data);
var_dump($final);
echo json_encode($final);
https://3v4l.org/736lQ

PHP JSON: Get value from siblings reference

I am working on a project that requires reading data from this terrible API that responds with terrible structured JSON data:
"finn-contanct": {...}
"finn-adata": {
"#attributes": {
"model": "https://cache.api.finn.no/iad/ad/model/car-used-sale"
},
"finn-field": [
{
"#attributes": {
"name": "authorized_dealership",
"value": "true"
}
},
{
"#attributes": {
"name": "body_type",
"value": "Stasjonsvogn"
}
},
{
"#attributes": {
"name": "car_location",
"value": "Norge"
}
},
{
"#attributes": {
"name": "engine"
},
"finn-field": [
{
"#attributes": {
"name": "effect",
"value": "90"
}
},
{
"#attributes": {
"name": "fuel",
"value": "Diesel"
}
}
]
},
{...},
]
}
How can i dynamically get the values under each attribute based on the siblings name value? Ideally with a function that accepts one parameter that finds the value in there by providing a key corresponding to the value i'm looking for.
Here is an example of what i'm expecting:
Given a function that expects one parameter: getAttrValue('key') I want to get the value under the #attributes sibling. So if I use the function like this: getAttrValue('body_type') i'm simply expecting this back: Stasjonsvogn. I don't really care about nested items. So if I do this: getAttrValue('fuel') I'm simply expecting: Diesel
I found this answer here on SO. But the problem with that method is that it doesn't work well with nested items. So does anyone have a method that would work with the data-structure I got above here?
The response is a total mess and I don't know how to handle it, nor how to Google it properly. So any help would be appreciated greatly.
Collect attributes into associative array recursively:
function collectAttributes($data)
{
$attributes = [];
$nodeAttribute = isset($data['#attributes']) ? $data['#attributes'] : [];
//collect current node attribute value
if (isset($nodeAttribute['name'])) {
$attributes[$nodeAttribute['name']] = isset($nodeAttribute['value']) ? $nodeAttribute['value'] : '';
}
//collect nested attributes recursively
foreach ($data as $nestedNode) {
if (is_array($nestedNode)) {
$attributes = array_merge($attributes, collectAttributes($nestedNode));
}
}
return $attributes;
}
And then use result as simple associative array:
$data = json_decode($inputJson, true);
$atttributes = collectAttributes($data);
echo $attributes['fuel']; //don't forget isset checking if you are not sure about content
But if you have attributes with same name you'll see only latest this way.

Getting all elements on a json schema using php

I really need help on this one.
I have the following Json Schema:
{
"url": "http://www.google.com",
"bodySchema": {
"type": "object",
"properties": {
"SKU": {
"sync": "True",
"mapTo": "SKU",
"type": "string"
},
"WareHouseId": {
"sync": "False",
"mapTo": "",
"type": "integer"
},
"Stock": {
"sync": "True",
"mapTo": "Stock",
"type": "integer"
}
},
"required": {
"0": "SKU",
"1": "Stock"
}
}
}
I would like to retrieve all elements and check if they are required or not,
On the first part (Getting all elements)
What I'm doing is:
foreach ($this->methods as $data) {
if(!empty($data['bodySchema']->properties)){
}
}
But my problem is that I have no way to get the SKU, WarehouseID or Stock, because it's not a key nor anything of the kind.
For my second issue what I was thinking, was to put all required as string and do a loop through them, but if there is any alternative would be glad to know.
You can get the properties out with a simple loop:
foreach ($data->bodySchema->properties as $key => $value) {
// ..
}
If you want to add the required field to the results from above, you can do it like so:
foreach ($data->bodySchema->required as $required) {
$data->bodySchema->properties->$required->required = true;
}
Example with objects or with arrays.

imploding array_keys from Facebook JSON data

Need some help with the sample code provided the facebook. I can't get it to return a series of IDs that I need to run a sql query against.
$friends = '{
"data": [
{
"name": "Paul",
"id": "12000"
},
{
"name": "Bonnie",
"id": "120310"
},
{
"name": "Melissa",
"id": "120944"
},
{
"name": "Simon",
"id": "125930"
},
{
"name": "Anthony",
"id": "120605"
},
{
"name": "David",
"id": "120733"
}
]
}';
$obj = json_decode($friends);
print $obj->{'data'}[0]->{'name'};
I can return the "Paul"
what I want is to return all the id's using implode(array_keys($obj),",")
I am only getting data to return.
What I'd like to do is retrieve all the IDs separated by a comma.
Thanks!
Try implode-ing on the data key with array_map:
function get_id($o) {
return $o->id;
}
implode(array_map('get_id', $obj->data),",")

Categories