代码之家  ›  专栏  ›  技术社区  ›  MB34

需要php数组搜索帮助

php
  •  1
  • MB34  · 技术社区  · 7 年前

    我有一个返回json的api函数,我这样调用它来转换为一个对象:

    $objParts = json_decode(file_get_contents("http://example.com/api/GetPartTypes"));
    

    这是 print_r($objParts) 结果:

    stdClass Object
    (
        [parttype] => Array
            (
                [0] => stdClass Object
                    (
                        [id] => 103
                        [desc] => Spoiler Valance, Fr
                        [l1] => Body & Frame
                        [l2] => Exterior/Interior Trim
                    )
    
                [1] => stdClass Object
                    (
                        [id] => 104
                        [desc] => Grille
                        [l1] => Body & Frame
                        [l2] => Hood
                    )
    
                [2] => stdClass Object
                    (
                        [id] => 105
                        [desc] => Bumper Assy, Front
                        [l1] => Body & Frame
                        [l2] => Hood
                    )
        )
    )
    

    我只想返回 id 匹配名为 $parttype 不使用 foreach() 循环。 ( $objParts 包含超过400个项目) 我知道 array_search() 但我不确定如何在上述情况下使用它。这不起作用:

    $parttype = 104;
    $val = array_search($parttype, $objParts);
    
    2 回复  |  直到 7 年前
        1
  •  0
  •   IncredibleHat    7 年前

    对于php 5x(而不是7),您必须将数组与函数一起使用,因此这是一个达到该结果的方法。

    混合 array_column array_search ,和 json_decode 在关联阵列模式下:

    $objParts = json_decode($yourjson,true); // include 'true' here
    $parttype = 104;
    $val = array_search($parttype, array_column($objParts['parttype'], 'id'));
    // $val will be '1' in this example
    
    $found = $objParts['parttype'][$val];
    

    要将其转换回stdclass的对象,请执行以下操作:

    $found = (object)$objParts['parttype'][$val];
    

    结果:

    stdclass对象 ( [ID]=104页 [说明]=>格栅 [L1]=>主体和框架 [L2]=>引擎盖 )

        2
  •  1
  •   Nigel Ren    7 年前

    如果您使用的是php 7及更高版本,则可以使用 array_column() 在对象上,所以只需添加…

    $objParts = json_decode(file_get_contents("t.json"));
    print_r($objParts);
    $parttype = 104;
    $item = array_search($parttype, array_column($objParts->parttype, "id"));
    
    echo $objParts->parttype[$item]->desc;
    
    推荐文章