¿Cómo ordeno un array PHP por un elemento anidado dentro?


Tengo una matriz como la siguiente:

Array
(
    [0] => Array
        (
            'name' => "Friday"
            'weight' => 6
        )
    [1] => Array
        (
            'name' => "Monday"
            'weight' => 2
        )
)

Me gustaría tomar los últimos valores de esa matriz (el 'peso'), y usarlo para ordenar los elementos principales de la matriz. Por lo tanto, en esta matriz, me gustaría ordenar por lo que el elemento' Lunes 'aparece antes del elemento' Viernes'.

Author: codaddict, 2010-09-13

8 answers

Puede utilizar usort as:

function cmp($a, $b) {
   return $a['weight'] - $b['weight'];
}

usort($arr,"cmp");
 37
Author: codaddict,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-13 15:34:31

Se puede hacer usando una función anónima .

También si su 'peso' es una cadena use uno de los otros retornos (vea las líneas comentadas):

<?php

$arr = array(
    0 => array (
        'name'   => 'Friday',
        'weight' => 6,
    ),
    1 => array (
        'name'   => 'Monday',
        'weight' => 2,
    ),
);

// sort by 'weight'
usort($arr, function($a, $b) { // anonymous function
    // compare numbers only
    return $a['weight'] - $b['weight'];

    // compare numbers or strings
    //return strcmp($a['weight'], $b['weight']);

    // compare numbers or strings non-case-sensitive
    //return strcmp(strtoupper($a['weight']), strtoupper($b['weight']));
});

var_export($arr);

/*
array (
    0 => array (
        'name'   => 'Monday',
        'weight' => 2,
    ),
    1 => array (
        'name'   => 'Friday',
        'weight' => 6,
    ),
)
*/
 6
Author: Geo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-18 17:49:04
 5
Author: PatrickS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-13 15:30:35

De acuerdo con usort, también a veces uso array_multisort ( http://ca2.php.net/manual/en/function.usort.php ) ejemplo 3, ordenar los resultados de la base de datos. Podrías hacer algo como:

<?php
$days = array(
  array('name' => 'Friday', 'weight' => 6),
  array('name' => 'Monday', 'weight' => 2),
);

$weight = array();
foreach($days as $k => $d) {
  $weight[$k] = $d['weight'];
}

print_r($days);

array_multisort($weight, SORT_ASC, $days);

print_r($days);
?>

Salida:

Array
(
    [0] => Array
        (
            [name] => Friday
            [weight] => 6
        )

    [1] => Array
        (
            [name] => Monday
            [weight] => 2
        )

)
Array
(
    [0] => Array
        (
            [name] => Monday
            [weight] => 2
        )

    [1] => Array
        (
            [name] => Friday
            [weight] => 6
        )

)
 3
Author: Konel Sum,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-13 15:46:43

También puede usar una función anónima.

usort($items, function($a, $b) {
    return $a['name'] > $b['name'];
});
 2
Author: Richard Ayotte,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-13 16:13:16

Si el campo ordenar por cadena como es title name,
array_multisort + Banderas para ordenamiento Natural y CaseInSensitivity son el camino a seguir:

$sort_by_title = array();
foreach($items as $item) {
  $sort_by_title [] = $item['title'];
}
array_multisort($sort_by_title , SORT_ASC, SORT_NATURAL | SORT_FLAG_CASE, $items );
 1
Author: d.raev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-26 14:31:06

Tenga en cuenta que si el elemento que está ordenando es un elemento flotante .0534 y .0353 (como para un porcentaje), entonces tienes que multiplicar ambos por 1000. no estoy seguro de por qué francamente... parece que usort parece comparar los valores enteros.

Me llevó un tiempo darme cuenta de eso...

Y 2 consejos que pueden no ser inmediatamente obvios:

  1. si sus matrices son objetos, puede usar return {a - >weight-{b - >weight of course
  2. si devuelve $b- > peso-a a- > peso, se ordenará desending.
 0
Author: Barry,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-17 01:18:42

Aquí hay una función genial que podría ayudar:

function subval_sort($a,$subkey,$sort) {
    foreach($a as $k=>$v) {
        $b[$k] = strtolower($v[$subkey]);
    }
    if($b)
    {
        $sort($b);
        foreach($b as $key=>$val) {
            $c[] = $a[$key];
        }
        return $c;
    }
}

Envía el array como $a la clave como $subkey y' asort ' o 'sort' para la variable $sort

 -1
Author: d2burke,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-13 15:51:01