10

これについても同様の質問と回答が投稿されていますが、どれも私のアレイの構造と完全には一致していないため、何かを見逃した場合はお詫びします。これは、WordPressのwpdbクラスによって生成された配列です。

Array ( 
[0] => Array ( [meta_id] => 37850 [post_id] => 5548 [meta_key] => Item # [meta_value] => 66002 ) 
[1] => Array ( [meta_id] => 37851 [post_id] => 5548 [meta_key] => Hex Size [meta_value] => .051" ) 
[2] => Array ( [meta_id] => 37852 [post_id] => 5548 [meta_key] => Across Flats [meta_value] => 0.051 ) 
[3] => Array ( [meta_id] => 37853 [post_id] => 5548 [meta_key] => Type [meta_value] => Hexagonal ) 
[4] => Array ( [meta_id] => 37854 [post_id] => 5548 [meta_key] => Shank [meta_value] => .315" ) ) 

Array ( 
[0] => Array ( [meta_id] => 37910 [post_id] => 5553 [meta_key] => Item # [meta_value] => 66008 ) 
[1] => Array ( [meta_id] => 37911 [post_id] => 5553 [meta_key] => Hex Size [meta_value] => 1/8" ) 
[2] => Array ( [meta_id] => 37912 [post_id] => 5553 [meta_key] => Across Flats [meta_value] => 0.127 ) 
[3] => Array ( [meta_id] => 37913 [post_id] => 5553 [meta_key] => Type [meta_value] => Hexagonal ) 
[4] => Array ( [meta_id] => 37914 [post_id] => 5553 [meta_key] => Shank [meta_value] => .315" ) ) 

Array ( 
[0] => Array ( [meta_id] => 37862 [post_id] => 5549 [meta_key] => Item # [meta_value] => 66004 ) 
[1] => Array ( [meta_id] => 37863 [post_id] => 5549 [meta_key] => Hex Size [meta_value] => 1/16" ) 
[2] => Array ( [meta_id] => 37864 [post_id] => 5549 [meta_key] => Across Flats [meta_value] => 0.063 ) 
[3] => Array ( [meta_id] => 37865 [post_id] => 5549 [meta_key] => Type [meta_value] => Hexagonal ) 
[4] => Array ( [meta_id] => 37866 [post_id] => 5549 [meta_key] => Shank [meta_value] => .315" ) ) 

Array ( 
[0] => Array ( [meta_id] => 37886 [post_id] => 5551 [meta_key] => Item # [meta_value] => 66006 ) 
[1] => Array ( [meta_id] => 37887 [post_id] => 5551 [meta_key] => Hex Size [meta_value] => 3/32" ) 
[2] => Array ( [meta_id] => 37888 [post_id] => 5551 [meta_key] => Across Flats [meta_value] => 0.095 ) 
[3] => Array ( [meta_id] => 37889 [post_id] => 5551 [meta_key] => Type [meta_value] => Hexagonal ) 
[4] => Array ( [meta_id] => 37890 [post_id] => 5551 [meta_key] => Shank [meta_value] => .315" ) ) 

Array[meta_value]の順序でリストする必要があります。次に、配列を使用して、この順序で製品のテーブルを生成します。私は次の関数を使用していますが、意味のない結果が生成されます。

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

1 に答える 1

23

usort()を使用します。例:

$items = [
    ['id' => 3, 'item' => 'pc'],
    ['id' => 1, 'item' => 'mouse'],
    ['id' => 2, 'item' => 'kb'],
];

function compare_id($a, $b) {
    if ($a['id'] == $b['id']) return 0;
    return ($a['id'] < $b['id']) ? -1 : 1;
}

usort($items, 'compare_id');

var_dump($items);    

または匿名関数を使用する

usort($items, function ($a, $b) {
    if ($a['id'] == $b['id']) return 0;
    return ($a['id'] < $b['id']) ? -1 : 1;
});
于 2013-02-21T03:45:18.047 に答える