Search in array, like select?

前端 未结 3 1753
天涯浪人
天涯浪人 2021-01-28 03:32

My array with countries is:

$cars = array(
    [\'brand\' => \'bmw\', \'place_1\' => \'Munich\', \'place_2\' => \'Cologne\'],
    [\'brand\' => \'vw\         


        
3条回答
  •  伪装坚强ぢ
    2021-01-28 03:58

    If you don't have opportunity to rebuild your array as @Daniel suggested, then you have to iterate over it, something like this:

    $brand_to_find = 'bmw';
    $key_to_select = 'place_2';
    
    foreach ($cars as $car) {
        if ($car['brand'] == $brand_to_find) {
            echo $car[$key_to_select];
    
            // if you're sure that will be no
            // more `bmw` in your array - break
            break;
        }
    }
    

    All wrapped in a function:

    function findPlaceByBrand($cars, $brand_to_find, $key_to_select) 
    {
        $result = '';
    
        foreach ($cars as $car) {
            if ($car['brand'] == $brand_to_find) {
                $result = $car[$key_to_select];
    
                // if you're sure that will be no
                // more `bmw` in your array - break
                break;
            }
        }
    
        return $result;
    }
    
    echo findPlaceByBrand($cars, 'bmw', 'place_2');   // Cologne
    echo findPlaceByBrand($cars, 'vw', 'place_1');    // Berlin
    echo findPlaceByBrand($cars, 'honda', 'place_1'); // empty string
    

提交回复
热议问题