How to access sub array within array elements? - php

Here is a api response. What I am having problem is that there are several crew member here. I can just get anyone by their basic index. What do I do to get just the writers name or Should I say how can I access the array with Writer as parameter and get his/her name from this array.
"crew": [
{
"credit_id": "53f52157c3a36833fa002225",
"department": "Writing",
"gender": 2,
"id": 1930,
"job": "Writer",
"name": "Truman Capote",
"profile_path": "/kmhddndt7hI38aN6NzbhPcnjKSh.jpg"
},
{
"credit_id": "52fe4a6ec3a368484e152e99",
"department": "Directing",
"gender": 1,
"id": 96199,
"job": "Director",
"name": "Liz Garbus",
"profile_path": "/1Z5a6djeDX57yyLe2ixX3VzIaLJ.jpg"
},
{
"credit_id": "53f5216dc3a36833fd0021bd",
"department": "Writing",
"gender": 1,
"id": 96199,
"job": "Writer",
"name": "Liz Garbus",
"profile_path": "/1Z5a6djeDX57yyLe2ixX3VzIaLJ.jpg"
},
{
"credit_id": "53f52180c3a36834000023b2",
"department": "Writing",
"gender": 0,
"id": 1355119,
"job": "Writer",
"name": "Ralph Greenson",
"profile_path": null
}
]
Thanks in Advance for any help.

With PHP you can use FilterIterator classes like in the following example ...
class CrewFilter extends FilterIterator {
protected $department;
public function __construct(Iterator $iterator, $department) {
$this->department = $department;
parent::__construct($iterator);
}
public function accept(): bool
{
$current = $this->getInnerIterator()->current();
return $current->department === $department;
}
}
$data = json_decode($response);
$iterator = new ArrayIterator($data['crew']);
$filter = new CrewFilter($iterator, 'Writing');
foreach ($filter as $crew) {
// output the name
var_dump($crew->name);
}
What does the code above. The FilterIterator instance takes a $department parameter, that sets the department for the crew memebers you want to see. The first parameter is an instance of an Iterator. In this case this will be the json decoded data from the api. It 's elementary to decode the received json data.
The foreach loop will just give back the crew members with the department Writing.

if you want to search from browser side assume ur api response json is in obj here is the javascript code
var results = [];
var searchField = "job";
var searchVal = "Writer";
for (var i=0 ; i < obj.crew.length ; i++)
{
if (obj.list[i][searchField] == searchVal) {
results.push(obj.list[i]);
}
}
then the result variable will have all the writers data
hope this is the solution you are searching for

If you want to process JSON object in php then try following code
<?php
// JSON string
$someJSON = '[{"name":"Jonathan Suh","gender":"male"},{"name":"William Philbin","gender":"male"},{"name":"Allison McKinnery","gender":"female"}]';
// Convert JSON string to Array
$someArray = json_decode($someJSON, true);
print_r($someArray); // Dump all data of the Array
echo $someArray[0]["name"]; // Access Array data
// Convert JSON string to Object
$someObject = json_decode($someJSON);
print_r($someObject); // Dump all data of the Object
echo $someObject[0]->name; // Access Object data
?>
Or if you want to process the data in Javscript (client side)
obj = [{
"credit_id": "53f52157c3a36833fa002225",
"department": "Writing",
"gender": 2,
"id": 1930,
"job": "Writer",
"name": "Truman Capote",
"profile_path": "/kmhddndt7hI38aN6NzbhPcnjKSh.jpg"
},
{
"credit_id": "53f52157c3a36833fa002225",
"department": "Writing",
"gender": 2,
"id": 1930,
"job": "Writer",
"name": "Truman Capote 2",
"profile_path": "/kmhddndt7hI38aN6NzbhPcnjKSh.jpg"
},
]
obj.forEach(function(v,i){console.log(v.name)})

So based on everyone's suggestion I tried tweaking somethings though it's not fast but much effective.(PHP Code)
$data = json_decode($response,true);
$n = sizeof($data['crew']);
for ($i=0; $i < $n; $i++) {
if($data['crew'][$i]['job']=='Writer')
{
echo $data['crew'][$i]['name'];
}
}

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

How to delete JSON Element in PHP?

I have a JSON object key element that i want to delete.
Lets say i want to delete the element of everything inside 'v8fe3m'
I tried using unset and delete. Nothing seems work unless my syntax is wrong.
{
"projects": {
"587ye4": {
"name": "abc",
"ip": "zz",
"loc": "azz"
},
"v8fe3m": {
"name": "japan",
"ip": "aaa",
"loc": "123",
"backups": {
"HELLO_1595524710053": {
"ts": 1595524710053,
"name": "HELLO",
"size": 770641
},
"HELLO_1595524717330": {
"ts": 1595524717330,
"name": "HELLO",
"size": 770641
},
"HELLO_1595524717558": {
"ts": 1595524717558,
"name": "HELLO",
"size": 770698
}
}
},
"x0190a": {
"name": "dubai",
"ip": "101",
"loc": "UAE"
}
}
}
$user_token = $_SESSION["userToken"];
$user_projects_json = read_json($GLOBALS['URL_JSON'] . "$user_token" . "_projects" .".json");
$projectKey = $_REQUEST['dataKey'];
$projectKey = trim($projectKey," ");
//v8fe3m
$backups = $user_projects_json['projects'][$projectKey];
unset($backups);
Since PHP is a strange language, it copies objects. Therefore $backups is a copy of $user_projects_json['projects'][$projectKey].
$backups = $user_projects_json['projects'][$projectKey];
unset($backups); //You are unsetting a very new object.
You can do
$backups = &$user_projects_json['projects'][$projectKey];
unset($backups); //You are unsetting a reference that refers to your object.
This way $backups are referring to your original object, thus unsetting what you need. I saw someone did it in the comments, but there were no explanation, unsetting without creating a new object.
First use $arrayFromJson = json_decode($yourJsonObject, true);, then you can use standard PHP array functions such as:
unset($arrayFromJson['v8fe3m']);

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

Accessing array inside array

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.

Foreach empty from json

I have the following url:
https://graph.facebook.com/123456/likes?access_token=__ACCESS_TOKEN__&format=json
which I then do:
$likesList = json_decode(file_get_contents("https://graph.facebook.com/123456/likes?access_token=$access_token&format=json"),true);
which produces e.g.
{
"data": [
{
"name": "yo yo yo",
"category": "Entertainer",
"id": "45640987076",
"created_time": "2012-04-18T16:14:09+0000"
},
{
"name": "Tony Smith",
"category": "Musician/band",
"id": "456456456456",
"created_time": "2012-02-22T06:56:18+0000"
},
{
"name": "Stations",
"category": "Company",
"id": "567657567",
"created_time": "2012-01-30T23:08:39+0000"
}
]
}
and I then want to list e.g. all the names returned so:
foreach ($likesList->data as $element2){
$name = $element2[name];
echo $name;
}
But it's empty?
See this visualization of your data structure.
As you are receiving an array, you need $list["data"] and not $list->data. Also don't forget to quote the array key "name".
foreach ($likesList['data'] as $element2){
$name = $element2['name'];
echo $name;
}
After json_decode with parameter true you will have associative array. You can access to value by string key. Like in example above.

Categories