用php从mysql构建一个多维数组

时间:2011-03-17 23:35:43

标签: php mysql multidimensional-array

我试图从mysql结果集中形成一个特定的多维数组。

我希望它看起来像这样:

array(
'product_name' => 'prod_1',
'categories' => array(1,2,3,4)
);

db结果返回一个类似于

的数组
Array
(
[0] => Array
    (
        [id] => 1
        [product_name] => prod_1
    )

[1] => Array
    (
        [id] => 2
        [product_name] => prod_1
    )

[2] => Array
    (
        [id] => 3
        [product_name] => prod_1
    )

[3] => Array
    (
        [id] => 4
        [product_name] => prod_1
    )

如您所见,我想将产品名称分组并将ID放入另一个数组

有没有人有关于如何做到这一点的任何提示?

3 个答案:

答案 0 :(得分:0)

$yourarray = array(array('id'=>1, 'product_name' => 'prod_1'), array('id'=>2, 'product_name' => 'prod_2'),array('id'=>3, 'product_name' => 'prod_3'));
$multiarray = array();

for($i=0; $i<count($yourarray);$i++){
    $multiarray['product_name'][] = $yourarray[$i]['product_name'];
    $multiarray['product_id'][] = $yourarray[$i]['id'];
}

print_r($yourarray); //original array
print_r($multiarray); //gives you multi array

类似的东西?

你的原始阵列:

Array
(
    [0] => Array
        (
            [id] => 1
            [product_name] => prod_1
        )

    [1] => Array
        (
            [id] => 2
            [product_name] => prod_2
        )

    [2] => Array
        (
            [id] => 3
            [product_name] => prod_3
        )

)

结果将打印出来:

Array
(
    [product_name] => Array
        (
            [0] => prod_1
            [1] => prod_2
            [2] => prod_3
        )

    [product_id] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )
)

答案 1 :(得分:0)

您是否尝试过GROUP_CONCAT。它类似于:

SELECT name, GROUP_CONCAT(name) AS friends FROM friendships GROUP BY name;

请在此处查看详细信息:http://forums.mysql.com/read.php?10,287931,287936#msg-287936

答案 2 :(得分:0)

$yourarray = array(array('id'=>1, 'product_name' => 'prod_1'), array('id'=>2, 'product_name' => 'prod_1'), array('id'=>3, 'product_name' => 'prod_1'),array('id'=>4, 'product_name' => 'prod_1'));

$multiarray = array();
foreach ($yourarray as $value) {
    if(!isset($multiarray['product_name'])) {
        $multiarray['product_name'] = $value['product_name'];
    }    
    $multiarray['categories'][] = $value['id'];
}
print_r($multiarray);