PHP变量不会分配给数组值

时间:2018-05-24 11:11:20

标签: php arrays

我正在尝试从下面的数组中分配$totalPrice一个值,但它只返回0,如果我使用echo $ sites [$ site],则回显$totalPrice在某些HTML代码中[0]它会显示值,但不会将其分配给$totalPrice

$totalPrice = 0;
$site = "UM";

$totalPrice = $sites[$site][0];


    $sites = array
    (
        "US" => array (38.78, 11, 5.5),
        "UM" => array (44.55, 11, 5.5),
        "PS" => array (55.28, 11, 5.5),
        "PM" => array (66.55, 11, 5.5)
    )

    echo $totalPrice; 

2 个答案:

答案 0 :(得分:2)

$totalPrice = 0;
$site = "UM";

$sites = array
(
    "US" => array (38.78, 11, 5.5),
    "UM" => array (44.55, 11, 5.5),
    "PS" => array (55.28, 11, 5.5),
    "PM" => array (66.55, 11, 5.5)
);
$totalPrice = $sites[$site][0];


echo $totalPrice; 

您在初始化之前使用了$totalPrice = $sites[$site][0];变量$sites,这就是为什么每次都给出答案0的原因。

答案 1 :(得分:2)

您可以尝试此代码..您需要在数组值...

下面声明$totalPrice
$totalPrice = 0;
$site = "UM";


    $sites = array(
        "US" => array (38.78, 11, 5.5),
        "UM" => array (44.55, 11, 5.5),
        "PS" => array (55.28, 11, 5.5),
        "PM" => array (66.55, 11, 5.5)
    );

    $totalPrice = $sites[$site][0];
echo $totalPrice;