1

I have an array like this

 0 => array:4 [▼
    "Name" => "Aroma Therapy - 45 minutes"
    "ID" => "1000000015"
    "Price" => "50.00"
    "Category" => "Aroma"
  ]
  1 => array:4 [▼
    "Name" => "Aroma Therapy - 60 Minutes"
    "ID" => "0000000003"
    "Price" => "100.00"
    "Category" => "Aroma"

What I am trying to achieve is that, whenever a user searches for 'therapy' or 'aroma', I want to match with this array's name and return it's price and ID.

I tried using strpos() strstr() and regular expressions as well, I can find if the search matches or not but I cannot get the functionality of returning the array when matched.

So, if a user searches for 'therapy', I want to return the two arrays above, in a variable called $result. So I can access it's name, ID and price like this

$result->Name, $result->ID, $result->Price

Any ideas on how to achieve this kind of functionality?

1
  • @WilliamPerron If you read my question, I have mentioned that I have tried using strpost(), strstr() and regular expressions, but I am unable to return the matched array Commented Nov 6, 2017 at 15:21

1 Answer 1

3

Using array_filter and stripos(), you can get array items

stripos — Find the position of the first occurrence of a case-insensitive substring in a string

array_filter — Filters elements of an array using a callback function

// keyword to be searched
$keyword = 'aroma';

// you will get all array items of matched 
$result_array = array_filter($array, function($item) use ($keyword) {
        return ( stripos($item['Name'], $keyword) !== false );
});

// to convert to object
$object = json_decode( json_encode($result_array) );
Sign up to request clarification or add additional context in comments.

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.