0

I have an odd question which I cannot find an answer to on Google or SO.

I have an array containing all the bits of information about the pages on my website. So the array contains multiple of the arrays like the example below:

'home' => 
array (size=7)
  'title' => string '' (length=0)
  'url' => string 'home.php' (length=8)
  'mobile' => string 'home.php' (length=8)
  'keywords' => string '' (length=0)
  'description' => string 'test123' (length=126)
  'login_needed' => boolean false
  'original_page' => string 'home' (length=4)

What I need to do is to find each array that contains a value that comes from a search bar. For example if the user searches for "bruidsmode" every array that contains "bruidsmode" should be put into another array which I can then output into elements to display on the website.

Below you will find a stripped example of what I have on my page. (I tried making a working example but was unable to do so):

<?php 
$config['menu']["home"] = array (
  'title'       => '',
  'url'             => 'home.php',
  'mobile'      => 'home.php',
  'keywords'        => '',
  'description'     => '',
  'login_needed'    => FALSE
);

$config['menu']["bruidsmode"] = array (
  'title'       => '',
  'url'             => 'bruidsmode.php',
  // 'mobile'           => 'bruidsmode.php',
  // 'mobile'       => 'bruidsmode.php',
  'keywords'        => '',
  'description'     => '',
  'login_needed'    => TRUE,
  'robot'           => FALSE
);

if(isset($_POST['generalsearch']) && isset($_POST['generalsearchresult'])){
// Put search value into variable
$searchvalue = $_POST['generalsearchresult'];

// Fill variable with all page items
$array = $config['menu'];
// Set search cretaria to search in array
$key = $searchvalue;
// Search for key value inside array
$result = @$array[$key] ?: null;

if($result == null){
    echo "Geen resultaten gevonden...";
}else{
    var_dump($result);
}
}
?>

<form method="POST">
  <input type="text" name="generalsearchresult">
  <input type="submit" name="generalsearch">
</form>

The above code works but only outputs arrays which exactly match the search criteria. So for example the searchterm "bruidsmode" with the above code outputs only the page "bruidsmode" but not the page "bruidsmode-overzicht" for example.

I hope the above is understandable, if not please tell me how to improve it.

Kind regards, Robbert

6
  • 1
    please exampld your question to show enough data to reproduce, for example a minimal example of what $config['menu'] contains. It looks like its a multidimentional array, and you are searching against the top level keys ('home', 'bruidsmode'...). Its not clear if you intend to search against the lower level array values (title. description etc), or if you would want to return multiple results Commented Jan 11, 2019 at 11:40
  • I doubt that code you posted actually is the code you are using. That code is syntactically faulty and does not compare any values. Commented Jan 11, 2019 at 11:41
  • 1
    @Granny is performing the 'search' by trying to get the specific key out of $array on line #10. Commented Jan 11, 2019 at 11:43
  • @arkascha The site is currently in development and that is the code I am currently using to find the search value in the array. But thats pretty much all it does. It just searches the array. Commented Jan 11, 2019 at 11:43
  • No, it does not. It would match an array entry with a key matching the search term which definitely is not what you want and describe. Commented Jan 11, 2019 at 11:48

2 Answers 2

1

Your code isn't really what I would call a search. In order to search you should loop over the array to find potential matches, rather than return the requested property.

function searchMenu($menu, $term) {
    $matches = [];
    foreach($menu as $key => $value) {
        if (stripos($key, $term) !== false) {
            $matches[] = $value;
        }
    }
    return $matches;
}


if(isset($_POST['generalsearch']) && isset($_POST['generalsearchresult'])){
    $result = searchMenu($config['menu'], $_POST['generalsearchresult']);
    if(!count($result)){
        echo "Geen resultaten gevonden...";
    }else{
        var_dump($result);
    }
}
Sign up to request clarification or add additional context in comments.

13 Comments

This does give me a result but not the correct one. If I for example search for "zoeken" it will output the home array which does not contain "zoeken" at all. It does not matter which value I input, it wil pretty much always output the home array (as in the example) with any search value.
My bad, had a typo on the comparison. Fixed the answer by replacing !== -1 to !== false.
Ah! There we go! It does now work. Now I need to figure out how to get each value to be outputted :)
In that case, the updated answer does what you need.
It loops through $config['menu'], and any keys that have the search term are added to the $matches array. $matches is then returned. If no matches are found the response will be an empty array.
|
0

If you want to return multiple results, you will need to store them in an array and return that.

If you are going to do that, you can extend the search to check against child fields as well, not just the top level keys:

$page_data =[

    'my-cat' => [
      'title'            => '',
      'url'              => 'my-cat.php',
      'mobile'           => 'my-cat.php',
      'keywords'         => 'cat,kitten',
      'description'      => 'i love my cat',
      'login_needed'     => false,
      'original_page'    => 'mycat',
    ],

    'home' => [
      'title'            => '',
      'url'              => 'home.php',
      'mobile'           => 'home.php',
      'keywords'         => 'cat,dog,other',
      'description'      => 'a site about cats',
      'login_needed'     => false,
      'original_page'    => 'home',
    ],

    'about' => [
      'title'            => '',
      'url'              => 'about.php',
      'mobile'           => 'about.php',
      'keywords'         => 'about',
      'description'      => 'about me',
      'login_needed'     => false,
      'original_page'    => 'about',
    ],
];

function search(array $page_data_to_search, string $search_term, array $fields_to_search): array{

    $out=[];
    $search_fields = array_flip($fields_to_search); //O(1)
    foreach($page_data_to_search as $key => $page_data){
        //first test the key
        if(isset($search_fields['key']) && strpos($key, $search_term) !==false){
            $out[$key]=$page_data;
            continue; //no need to check other fields
        }
        //then the user supplied fields
        foreach($search_fields as $field => $unused){
            if(isset($page_data[$field]) && strpos($page_data[$field], $search_term) !==false){
                $out[$key]=$page_data;
                break;
            }
        }
    }
    return $out;

}

echo '<pre>';
var_dump(search($page_data, 'cat', ['key', 'keywords', 'description']));

Comments

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.