如何从具有多个键和值的多维数组中获取唯一键和相关值的数组

时间:2013-06-07 12:58:06

标签: php mysql sql codeigniter

我正在针对特定的表触发查询并获得此结果:

        $results = array(3) {
          [0]=>
          array(2) {
            ["category"]=>
            string(1) "1"
            ["manufacturer"]=>
            string(1) "2"
          }
          [1]=>
          array(2) {
            ["category"]=>
            string(1) "1"
            ["manufacturer"]=>
            string(1) "9"
          }
          [2]=>
          array(2) {
            ["category"]=>
            string(1) "1"
            ["manufacturer"]=>
            string(2) "10"
          }
        }

我尝试了很多解决方案,如:

        $temp = array();
        foreach ($results as $result) {
            foreach ($result as $key => $value) {               
                 $data = array_merge($temp[$key], $value);
            }
        }

    foreach ($results as $result) {
                foreach ($result as $key => $value) {
                    array_push($temp[$result], $value);
                }
            }

我希望类别的值作为数组的索引和制造商的值作为关联类别(索引)的数组。如下图所示:

$array = array(1) {
[1]=> array(3) {
     2,9,10
     }
};

1 个答案:

答案 0 :(得分:1)

Live demo此代码:

$temp = array();
foreach($results as $result){
    $temp[$result['category']][] = $result['manufacturer'];
}

按要求输出:

array(1) {
    [1]=>
    array(3) {
        [0]=>
        string(1) "2"
        [1]=>
        string(1) "9"
        [2]=>
        string(2) "10"
    }
}

注意:All PHP arrays are associative arrays,所以你无法摆脱数组中的0,1,2索引。