Foreach结果为行根据名称排序到不同的数组中

时间:2014-06-03 10:58:54

标签: php arrays oracle foreach

我正在尝试熟悉ORACLE并使用PHP和ORACLE ..我在数据库中有一个表格如下:

| rec_id | red   | orange |
| rec_id | yellow| orange |
| rec_id | green | apple  |
| rec_id | red   | apple  |
| rec_id | green | lime   |
| rec_id | red   | grape  |
| rec_id | red   | carrot |

..我需要创建多维数组,如:

array
    0=>orange{
         0=>red,
         1=>yellow}
    1=>apple{
         0=>green,
         1=>red}
    2=>lime{
         0=>green}
   etc..

使用foreach($result as $row)做最快最安全的方法是什么?

由于

2 个答案:

答案 0 :(得分:1)

<?
$out = array();
foreach($result as $row)
    $out[$row['fruit']][] = $row['color'];
}
print_r($out);

?>

如果你需要每个水果的唯一数组,这里有两种可能的方法。

//two loops
$out = array();
foreach($row as $r){
    $out[$r['fruit']][] = $r['color'];
}
foreach($out as $i > $o){
    $out[$i] = array_unique($o);
}
print_r($out);



//one loop
$out = array();
foreach($row as $r){
    $out[$r['fruit']] = isset($out[$r['fruit']]) ? $out[$r['fruit']] : array();
    if(!in_array($r['color'],$out[$r['fruit']])){
        $out[$r['fruit']][] = $r['color'];
    }
}
print_r($out);

答案 1 :(得分:1)

一个简单的foreach就足够了。在循环下,将fruits设置为键,然后附加colors。考虑这个例子:

$values_from_db = array( array('rec_id' => 1, 'color' => 'red', 'fruit' => 'orange'), array('rec_id' => 2, 'color' => 'yellow', 'fruit' => 'orange'), array('rec_id' => 3, 'color' => 'green', 'fruit' => 'apple'), array('rec_id' => 4, 'color' => 'red', 'fruit' => 'apple'), array('rec_id' => 5, 'color' => 'green', 'fruit' => 'lime'), array('rec_id' => 6, 'color' => 'red', 'fruit' => 'grape'), array('rec_id' => 7, 'color' => 'red', 'fruit' => 'carrot'),);
$new_values = array();
foreach($values_from_db as $key => $value) {
    $new_values[$value['fruit']][] = $value['color']; 
}
print_r($new_values);

应该导致类似:Fiddle

Array
(
    [orange] => Array
        (
            [0] => red
            [1] => yellow
        )

    [apple] => Array
        (
            [0] => green
            [1] => red
        )

    [lime] => Array
        (
            [0] => green
        )

    [grape] => Array
        (
            [0] => red
        )

    [carrot] => Array
        (
            [0] => red
        )

)