0

I have a json array in a json file, this is brought into a $data variable $data = file_get_contents("json/data.json");. Two of the attribute names are commonName and elementName, these will be passed through the url.

With the json file in the data variable I would like to filter on two attributes and then echo the result.

I'm getting the following error:

Warning: array_filter() expects parameter 1 to be array, string given in

Here's my current code:

<?php
  function myfilter($row){
      return ($row['commonName']=='goat' && $row['elementName']=='calcaneus');
  }
  $result = array_filter($data, 'myfilter');

  echo '<pre>';
  echo 'json array{';

    foreach($result as $elem)  {
      echo(
        $elem['institutionID']. ", ".
        $elem['scientificNameID']. ", ".
        $elem['scientificName']. ", ".
        $elem['kingdom']. ", ".
        $elem['phylum']. ", ".
        $elem['class']. ", ".
        $elem['order']. ", ".
        $elem['family']. ", ".
        $elem['genus']. ", ".
        $elem['subgenus']
      );
      echo("<br/>");
    }
    echo '</pre>';
  //
    echo '}';
?>

edit:

original json code snippet:

[
  {
    "type": "",
    "modified": "",
    "language": "",
    "license": "",
    "rightsHolder": "",
    "accessRights": "",
    "bibliographicCitation": "",
    "references": "",
    "institutionID": "Phoneome10k",
    "collectionID": "",
    "datasetID": "",
    "institutionCode": "",
    "collectionCode": "",
    "datasetName": "",
    ...
1
  • 1
    maybe you have to convert $data with json_decode first? Commented Nov 28, 2020 at 16:00

1 Answer 1

1

Try changing this:

$data = file_get_contents("json/data.json");
$data = json_decode(file_get_contents("json/data.json"));

As file_get_contents returns a string, you encode it into an array using json_decode.

Sign up to request clarification or add additional context in comments.

6 Comments

That gives: Fatal error: Uncaught Error: Cannot use object of type stdClass as array in
I've added a snippet of the json code that was brought in. var_dump($data); shows all the data as expected.
@SpatialDigger Just add true as a second parameter to json_decode to get an array instead of an stdClass object.
I've added True all the data is displayed, but the filter is not applied.
@SpatialDigger Now that becomes another question, doesn't it? Try to do some basic debugging, dump the values inside your filter function and try to identify why the matches aren't being made.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.