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.
The return value in the getPartByName function can only return one element.
If you want multiple results, then you should return an array.
Try it online (Text updated to make it easier to understand than using encoded characters)