简体   繁体   English

如何在php中获取关联数组值?

[英]how to get associative array value in php?

I have an associative array in php that looks like this 我在php中有一个关联数组,看起来像这样

incSched={"62":"10878","63":"10878","64":"10878","65":"10878","66":"28416","67":"28416","68":"28416","69":"28416","70":"28416"}

How do I access the value for "62"? 如何访问“ 62”的值?

I've tried 我试过了

$amt = $incSched[$j];
$amt = $incSched["$j"];
$amt = $incSched[strval($j)];

they all return an empty string. 它们都返回一个空字符串。

Here is the full loop so you can see what $j is: 这是完整的循环,因此您可以看到$ j是什么:

$startAge = 53;
for ($i=0; $i<count($incTableIds); $i++) {
    $tableId = $incTableIds[$i];
    for ($j=$startAge; $j<101; $j++) {
        $incSched = $incomeSchedules[$tableId];
        echo "incSched=" .json_encode($incSched) ."<br>";
        $amt = $incSched["$j"];
        if ($amt == "") $amt = 0;
        if ($j>$startAge) $amt = $incSchedules[$tableId][$j-1]; //use previous value
        echo "Income: tableId=$tableId, age=$j, amt=$amt<br>";
        $incSchedules[$tableId][$j] = $amt;
    }
}

Here is the output when the loop hits 62 这是循环达到62时的输出

Income: tableId=1, age=62, amt=0

amt should be 10878, not 0. Any ideas? amt应该是10878,而不是0。有什么想法吗?

You are using the JSON Format but without the quotes. 您正在使用JSON格式,但没有引号。 In order to decode the JSON format, you'll have to convert your value into a JSON string. 为了解码JSON格式,您必须将值转换为JSON字符串。 Try this below code: 试试下面的代码:

// $incSched = '[{"62":"10878"},{"63":"10878"},{"64":"10878"},{"65":"10878"},{"66":"28416"},{"67":"28416"},{"68":"28416"},{"69":"28416"},{"70":"28416"}]';
$incSched = '{"62":"10878","63":"10878","64":"10878","65":"10878","66":"28416","67":"28416","68":"28416","69":"28416","70":"28416"}';
$incSched = json_decode($incSched, true);

foreach ($incSched as $key => $value) {
    echo $key . '=>'. $value . '<br />';
}

In the above, I have given you both the valid formats of JSON. 在上面,我给了您两种有效的JSON格式。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM