Cowgirl
Cowgirl

Reputation: 1494

Match an array value with a string and return the array PHP

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?

Upvotes: 1

Views: 41

Answers (1)

Akshay Hegde
Akshay Hegde

Reputation: 16997

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) );

Upvotes: 3

Related Questions