PHP - 数组错误输出(需要函数帮助)

时间:2016-06-07 10:41:50

标签: php arrays function

在此函数的输出中(最后),您可以看到产品放置在每个subArray中。我想通过需要添加产品的参数来传递函数。参数将是不同页面上的变量:如果变量具有值“meal2”=>只需要在“meal2”数组下添加产品。

function addToMeal() {

    $xmaaltijden = $_SESSION['xmaaltijden'];
    $i=1;

    while ( $i <= $xmaaltijden ) {

        $schemas = array('maaltijd' . $i);
        $i++;


    $producten = $_SESSION['products'];

    foreach ($schemas as $key => $schema){
        foreach ($producten as $k => $product){

             $variables[$schema][] = $product;
    };
};
};

echo '<pre>' . print_r($variables,1) . '</pre>';  
}   

输出:

Array
(
    [meal1] => Array
        (
            [0] => 1
            [1] => 3
            [2] => 2
            [3] => 9
        )

    [meal2] => Array
        (
            [0] => 1
            [1] => 3
            [2] => 2
            [3] => 9
        )

    [meal3] => Array
        (
            [0] => 1
            [1] => 3
            [2] => 2
            [3] => 9
        )

)

1 个答案:

答案 0 :(得分:0)

 foreach ($schemas as $key => $schema){
        foreach ($producten as $k => $product){

             $variables[$schema][] = $product;
    };

可是:

$yourVar = 'meal2';
foreach ($schemas as $key => $schema){
   if ($schema === $yourVar) {
       $variables[$schema] = $producten;
   } else {
       $variables[$schema] = array();
   }
}