Commit 3ffe085f authored by Адлан Шамавов's avatar Адлан Шамавов
Browse files

add search function

parent f0ad67ee
Loading
Loading
Loading
Loading
+19 −24
Original line number Diff line number Diff line
<?php
/**
* Выполняет сортировку массива по убыванию цены  *  
* @param array $array  *  
* @return array  
/*
*  
* Найдет элемент с указаным id  *  
* @param array $array - массив, содержащий элементы со структурой  * 
[  
* 'id' => 30,  *      
  'name' => 'Jhon',  *      
  'age' => 23,  * 
]  
* @param $id - ид искомого элемента  *  
* @return array - найденный элемент   
*/ 

function sortPrice(array $array): array {
    $price = [];
    $count = [];
    foreach ($array as $key => $row) {
        $price[$key]  = $row['price'];
        $count[$key] = $row['count'];
    }
    array_multisort($price, SORT_DESC, $count, SORT_ASC, $array);
    return $array;
function search($array, $id): ?array {
    $rowId = array_search($id, array_column($array, 'id'));
    return $array[$rowId];
}

//На выход должна вернуть отсортированный массив по ключу *price* DESC и во вторую очередь по *count* ASC:

//[ ['price'=>12, 'count'=>4],  ['price'=>10, 'count'=>2],  ['price'=>8, 'count'=>4],  ['price'=>8, 'count'=>5],  ['price'=>5, 'count'=>5], ]

?>

<!DOCTYPE html>
@@ -32,13 +28,12 @@ function sortPrice(array $array): array {
<body>
    <?php
        $array = [
            ['price'=>10, 'count'=>2],  
            ['price'=>5, 'count'=>5],  
            ['price'=>8, 'count'=>5],  
            ['price'=>12, 'count'=>4],  
            ['price'=>8, 'count'=>4], 
            ['id'=>10, 'name'=>'Jhon', 'age'=>23],  
            ['id'=>32, 'name'=>'Alex', 'age'=>34],  
            ['id'=>54, 'name'=>'Bob', 'age'=>45],  
            ['id'=>6, 'name'=>'Mike', 'age'=>61],
        ];
        print_r(sortPrice($array));
        print_r(search($array, 54));
    ?>
</body>
</html>
 No newline at end of file