search

Home  >  Q&A  >  body text

How to fill an array with JSON objects?

I have a file called parts.json, which is a JSON file containing an array of some vehicle spare parts objects.

Here is an example of some of them:


[
    {
        "name": "u0625u0643u0635u062fu0627u0645 u0623u0633u0648u062f u062eu0641u064au0641",
        "category": "u0625u0643u0635u062fu0627u0645u0627u062a",
        "quantity": "2",
        "price": "55",
        "id": 1756378,
        "shelf": "30",
        "slot": "173"
    },
    {
        "name": "u0625u0643u0635u062fu0627u0645 u0623u0633u0648u062f u0645u062du0645u0644",
        "category": "u0625u0643u0635u062fu0627u0645u0627u062a",
        "quantity": "2",
        "price": "90",
        "id": 1181335,
        "shelf": "",
        "slot": ""
    }

In my index.php file, I have a form that contains a text input box and a submit button. I want to add search functionality so that whenever the submit button is clicked, a form is populated with all the spare parts information.

For this, I created two functions as follows:


function getParts()
{
    return json_decode(file_get_contents(__DIR__ . '/parts.json'), true);
}

function getPartByName($name)
{
    $parts = getParts();
    foreach ($parts as $part) {
        if (str_starts_with($part['name'], $name)) {
            return $part;
        }
    }
    return '';
}

The problem is when I use this code:

$searchedPart = $_POST['searched-part'];
  $partToBeSearched = trim($searchedPart); 
  echo getPartByName($partToBeSearched)['name'];

What I get is the first occurrence of a spare part name starting with the entered prefix.

P粉470645222P粉470645222511 days ago457

reply all(1)I'll reply

  • P粉658954914

    P粉6589549142023-07-21 09:31:18

    The return value in the getPartByName function can only return one element.

    If you want multiple results, then you should return an array.

    1. We define an array in the method.
    2. We add an element to the array for each element corresponding to the filter.
    3. We return this array.
    function getPartByName($name)
    {
        $matches = [];
    
        $parts = getParts();
        foreach ($parts as $part) {
            if (str_starts_with($part['name'], $name)) {
                $matches[] = $part;
            }
        }
    
        return $matches;
    }
    

    Try it online (Text updated to make it easier to understand than using encoded characters)

    reply
    0
  • Cancelreply