1
"cuisines": [
            {
                "id": 61,
                "name": "mexican"
            },
            {
                "id": 63,
                "name": "Indian"
            },
            {
                "id": 64,
                "name": "Thai"
            }
        ],

I want search in array like when i search with "m" new array will be.

"cuisines": [
                {
                    "id": 61,
                    "name": "mexican"
                }
            ],

How can i do that ?

Any suggestion ?

Thanks.

4
  • Filter as this role: if the name include the char "m"? Commented Dec 6, 2018 at 11:59
  • what you have tried so far ? Commented Dec 6, 2018 at 11:59
  • You've provided a JSON instead of an array. Are you sure you want to parse an array and do a regex? Commented Dec 7, 2018 at 4:22
  • <?php $json = '{"cuisines": [{"id": 61, "name": "mexican"}, {"id": 63, "name": "Indian"},{ "id": 64,"name":"Thai"}]}'; function filterArray($element, $key = "i") { return (stripos($element['name'], $key) !== false & 1); } $array = json_decode($json, true); $needle = "m"; $filteredArray = array(); $filteredArray["cuisines"] = array_filter($array["cuisines"], function($elem) use($needle){ return (stripos($elem['name'], $needle) !== false & 1); }); echo json_encode($filteredArray); ?> Commented Dec 7, 2018 at 5:02

2 Answers 2

1

You can use array_filter and stripos:

$search = 'm';

$array = [
    "cuisines" => [
            [
                "id" => 61,
                "name" => "mexican"
            ],
            [
                "id" => 63,
                "name" => "Indian"
            ],
            [
                "id" => 64,
                "name" => "Thai"
            ]
        ],
];

$array['cuisines'] = array_filter($array['cuisines'], function ($item) use ($search) {
    return stripos($item['name'], $search) !== false;
});
Sign up to request clarification or add additional context in comments.

2 Comments

How to print return value ?
what do you mean? you can loop over the $array['cuisines'] and print the results
1

array_filter can be a solution. Example:

<?php
$data = '{"cuisines": [
    {
        "id": 61,
        "name": "mexican"
    },
    {
        "id": 63,
        "name": "Indian"
    },
    {
        "id": 64,
        "name": "Thai"
    }
]}';

$data = json_decode($data, true);
$search = 'm';
$data = array_filter($data['cuisines'], function ($item) use ($search) {
    return !!(false !== strpos($item['name'], $search));
});

print '<pre>';
print_r($data);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.