Search in array, like select?

2019-03-04 17:29发布

问题:

My array with countries is:

$cars = array(
    ['brand' => 'bmw', 'place_1' => 'Munich', 'place_2' => 'Cologne'],
    ['brand' => 'vw', 'place_1' => 'Berlin', 'place_2' => 'Kopenhagen'],
    ['brand' => 'hyndai', 'place_1' => 'Miami', 'place_2' => 'Newyork'],
);

I can select a name with this command: $cars[1]['place_2'] the nr. 1 is position in array, but I need it by "brand" because this values are dynamic.

I need something like this: $cars['brand' => 'bmw']['place_2'] or $cars->brand['bmw']['place2'], but the syntax is incorrect.

How can I get name by code for example place2 from brand bmw, I think my array is correct and I need only true select?

My previous sources are:

PHP - find entry by object property from a array of objects

How to search in array of std object (array of object) using in_array php function?

Reference PHP array by multiple indexes

Some of this examples works, but no one is like select, is it possible in a array?

回答1:

Use your brands as array keys instead of using numeric array indexes.

Something like this

$cars = [
  'bmw' => ['place_1' => 'Munich', 'place_2' => 'Cologne'],
  'vw' => ['brand' => 'vw', 'place_1' => 'Berlin', 'place_2' => 'Kopenhagen'],
  'hyndai' => ['brand' => 'hyndai', 'place_1' => 'Miami', 'place_2' => 'Newyork'],
];

Then you can access the variables like you want to: $cars['bmw']['place_1']


P.S : "hyndai" is probably a typo - it's spelled Hyundai



回答2:

Not tested but something like this

   function arraySelect($arr,$brand){
        $selection=[];
        foreach($arr as $a){
                if($a["brand"]=$brand{
                        array_push($selection,$a);
                }
        }
        return $selection;
}


回答3:

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