简体   繁体   中英

How to access sub array within array elements?

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.

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

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 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'];
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM