搜索PHP数组值

时间:2018-12-06 11:57:02

标签: php arrays search

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

我想在数组中进行搜索,就像用“ m”搜索新数组一样。

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

我该怎么做?

有什么建议吗?

谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用array_filterstripos

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

答案 1 :(得分:1)

array_filter可以解决。示例:

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