【问题标题】:PHP - array wrong output (need function help)PHP - 数组错误输出(需要函数帮助)
【发布时间】:2016-10-07 05:22:25
【问题描述】:

在这个函数的输出(最后)中,您可以看到产品被放置在每个子数组中。我想通过需要添加产品的参数来传递函数。参数将是不同页面上的变量:例如,如果变量的值为“meal2” => product 只需要添加到数组“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
        )

)

【问题讨论】:

    标签: php arrays function


    【解决方案1】:

    不是:

     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();
       }
    }
    

    【讨论】:

    • 如何打印所有内容?
    • print_r($variables);
    • 我的代码正在将产品添加到您的特定名称中,而对于其他架构,它设置了空数组。
    • 是的,我知道,但是如何打印每个数组和值
    • 我不确定我现在是否理解你。你能告诉我你想收到的输出的例子吗?
    猜你喜欢
    • 1970-01-01
    • 2016-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多