在php中输入多维数组中的值

问题描述 投票:0回答:2

[我正在尝试通过2个数组创建一个多维数组 动态地通过循环两个数组。

代码

<?php
$days = ["Monday","Tuesday","Wednesday"];
$rates = [40,60,80];
$profit = [];

foreach($days as $day => $value){
    foreach($rates as $rate){
    $netprofit = $rate* 20;
     $profit[$value] = [$rate=> $netprofit];
    }


}
print_r($profit);

结果

Array
(
    [Monday] => Array
        (
            [80] => 1600
        )

    [Tuesday] => Array
        (
            [80] => 1600
        )

    [Wednesday] => Array
        (
            [80] => 1600
        )

)

预期结果

Array
(
    [Monday] => Array
        (
            [40] => 800
            [60] => 1200
            [80] => 1600
        )

    [Tuesday] => Array
        (
            [40] => 800
            [60] => 1200
            [80] => 1600
        )

    [Wednesday] => Array
        (
            [40] => 800
            [60] => 1200
            [80] => 1600
        )

)

我想循环$ days数组,并将其用作新数组$ profit的第一维的键。其次,我想将$ rates数组的值分配为第二维的键并分配一个值。我尝试过这种方法,但未找到预期的结果。

php arrays multidimensional-array foreach
2个回答
0
投票

尝试一下:

 $days = ["Monday","Tuesday","Wednesday"];
    $rates = [40,60,80];
    $profit = [];

    foreach($days as $day => $value){
      $x = array();
    foreach($rates as $rate){
      $x[$rate] =  $rate* 20;

    }
    $profit[$value] = $x;

    }
    print_r($profit);

0
投票

您需要套现利润:

foreach($days as $day){
    $profit[$day] = [];
    foreach($rates as $rate) {
        $netprofit = $rate * 20;
        $profit[$day][$rate] = $netprofit;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.