i have a big array with a lot of subarrays. Each subarray has a few values. Every subarray is an item and values are parameters of that item. I have a searchbar with a POST
method. One of the values of the item is name of the item. So if the client is looking for item_one
, I need to echo some piece of code with parameters of item_one
.
My array looks like this:
$database = [
[
'name'=> 'item_one',
'img_src'=> 'pictures/item_one.jpg',
'preview_href'=> 'item_site.php?id='.item_preview($database).'',
'description'=> 'This product is.....' ,
],
[
'name'=> 'item_two',
'img_src'=> 'pictures/item_two.jpg',
'preview_href'=> 'item_site.php?id='.item_preview($database).'',
'description'=> 'This product is.....' ,
],
// ...
];
and this piece of code i need to use for specific subarray:
echo '<div class="item">
<a href="' . $item['preview_href'] . '" title="' . $item['name'] . '">
<img src="' . $item['img_src'] . '">
<div class="item_description"> '
. $item['name'] . ' ('
. $item['release']
. ') </div>
</a>
</div>'
I have tried loads of different things, for example:
$post = $_POST['search'];
foreach ($database as $item) {
if ($item['name'] == $post) {
echo '<div class="item">
<a href="' . $item['preview_href'] . '" title="' . $item['name'] . '">
<img src="' . $item['img_src'] . '">
<div class="item_description"> ' . $item['name'] . ' (' . $item['release'] . ') </div>
</a>
</div>'
}
}
I have been trying for a few days so I will be happy for any advice. Thanks
Your code is not very forgiving. If the user does not type the name exactly as you have it in your database, you will not get a match.
I would try a couple of things.
if you need exact match:
if( strtoupper($post) === strtoupper($item['name']))
{ // item found}
or, if you want to search for substring, try
if( stripos($item['name'], $post) !== false)
{ //item was found }