Tsea Tsea - 4 months ago 16
PHP Question

How do I create a search function for a json array in php

I'm using CURL to retrieve a json list of projects. I'm trying to search each project and echo only the projects that have the search term. If any of the projects json fields match The search term I would like to display that project.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://url.com/api/projects");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Access-Token: CsdujazxcvSq0w"
));
$proj_srch = curl_exec($ch);
curl_close($ch);
$json = json_decode($proj_srch, TRUE);


The json looks like this

(
[success] => 1
[data] => Array
(
[0] => Array
(
[id] => 1088
[project_name] => Mission Church
[project_no] => 1088
[description] => ries, but also the leap into electronic typesetting, remaining essentially unchanged.
[institution_name] => Archdio
[address] => 35 Ptt Street
[city] => Suaa
[state_province] => Suaa
[country] => Fiji
[country_code] => fj
[postal_code] => 00000
[dio_name] => Dio of Suaa
[featured_image_url] => https://url.org/media/cd51ec97-2684-6ebb-48c8-89d00b9685d3.JPG
)

[1] => Array
(
[id] => 1100
[project_name] => Micro-financing
[project_no] => 1100
[description] => ries, but also the leap into electronic typesetting, remaining essentially unchanged.
[institution_name] => Missions of Africa
[address] => PO Box 9253
[city] => Macha
[state_province] => Macha
[country] => Kenya
[country_code] => ke
[postal_code] => 87199
[dio_name] => Dio of Macha
[project_leader] => 55
[project_leader_name] => Bowman
[status] => published
[featured_image_url] => https://url.com/media/31bdace8-a384-832c-3976-666f4d2f7bfd.JPG

)


This is what I tried with no success

if (strpos($json, 'search-term') !== false) {

foreach ($json['data'] as $key ) {
echo $key['project_name'];
}

}

Answer

You are decoding the JSON into an array, which is good, however you need to use array functions from then on. Example:

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://url.com/api/projects");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
      "Access-Token: CsdujazxcvSq0w"
    ));
    $proj_srch = curl_exec($ch);
    curl_close($ch);
    $json = json_decode($proj_srch, TRUE);

    $searchTerm = "search-term"; //Or whatever
    $json["data"] = array_filter($json["data"], function ($v) use ($searchTerm) { 
          foreach ($v as $entry) { 
                if (is_string($entry) && strpos($entry,$searchTerm) !== false) { return true; }
          }
          return false;
   });