ccc

Arrays: Ordenar array asociativo por campo concreto

function orderBy($items, $attr, $order) {
    $sortedItems = [];
    foreach ($items as $item) {
        $key = is_object($item) ? $item->{$attr} : $item[$attr];
        $sortedItems[$key] = $item;
    }
    if ($order === 'desc') {
        krsort($sortedItems);
    } else {
        ksort($sortedItems);
    }
    return array_values($sortedItems);
}


$arr = array(
["id" => 1, "nombre" => "Clark Gable", "anno" => "1934"],
["id" => 2, "nombre" => "Victor McLagen", "anno" => "1935"],
["id" => 3, "nombre" => "Paul Muni", "anno" => "1936"],
["id" => 4, "nombre" => "Spencer Tracy", "anno" => "1937"]
);


$newArr = orderBy($arr,'nombre','desc');

print_r($newArr);

No hay comentarios:

Publicar un comentario