我有这个php代码,因为我试图在我的php项目中执行一个特定的函数,我编码实现正确,但我遇到了一个小问题。
<?php echo '<script type="text/javascript">';
$data = array(
'base' => 'USD',
'alter' => 'ETH',
'data' => array()
);
foreach ($cryptos as $row) {
$sy = $row["symbol"];
$data['data'][] = array(
"$sy" => [
"rate" => 1.552000000000000,
"min" => 1.0077600000000000,
"max" => 10.077600000000000,
"code" => $row["symbol"],
"dp" => 8
],
);
}
print_r("var fxCur = " . json_encode($data));
运行上面的代码,我得到了下面的结果,这是预期的结果,但我想在data
之间省略[]{
"base":"USD",
"alter":"ETH",
"data":[
{
"BTC":{
"rate": 1.552000000000000,
"min": 1.0077600000000000,
"max": 10.077600000000000,
"code":"BTC",
"dp":8
}
},
{
"ETH":{
"rate": 1.552000000000000,
"min": 1.0077600000000000,
"max": 10.077600000000000,
"code":"ETH",
"dp":8
}
}
]
}
但实际上我想要这个结果
{
"base":"USD",
"alter":"ETH",
"data":{
"BTC":{
"rate": 1.552000000000000,
"min": 1.0077600000000000,
"max": 10.077600000000000,
"code":"BTC",
"dp":8
},
"ETH":{
"rate": 1.552000000000000,
"min": 1.0077600000000000,
"max": 10.077600000000000,
"code":"ETH",
"dp":8
},
}
}
你告诉它以这种方式构造数据结构。
$data['data'][] = array(
"$sy" => [
...
]
);
这行表示"在$data['data']
的下一个整数索引处添加一个元素,并将其设置为与数组相等,例如[ "BTC" => [ ... ]]
我认为你想要的是:
$data['data'][$sy] = [
"rate" => 1.552000000000000,
"min" => 1.0077600000000000,
"max" => 10.077600000000000,
"code" => $row["symbol"],
"dp" => 8
];