【问题标题】:Search for PHP array value [duplicate]搜索 PHP 数组值 [重复]
【发布时间】:2019-05-08 02:58:39
【问题描述】:
"cuisines": [
            {
                "id": 61,
                "name": "mexican"
            },
            {
                "id": 63,
                "name": "Indian"
            },
            {
                "id": 64,
                "name": "Thai"
            }
        ],

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

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

我该怎么做?

有什么建议吗?

谢谢。

【问题讨论】:

  • 按此角色过滤:如果名称中包含字符“m”?
  • 到目前为止你尝试了什么?
  • 您提供了 JSON 而不是数组。您确定要解析数组并执行正则表达式吗?

标签: php arrays search


【解决方案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);

【讨论】:

    【解决方案2】:

    您可以使用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;
    });
    

    【讨论】:

    • 如何打印返回值?
    • 什么意思?您可以遍历$array['cuisines'] 并打印结果
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    相关资源
    最近更新 更多