为什么以下代码:
if (isset($_GET['trainType']) && isset($_GET['onTime']) && isset($_GET['gotSeat'])) {
$train[0]['trainType'] = $_GET['trainType'];
$train[0]['trainType']['onTime'] = $_GET['onTime'];
$train[0]['trainType']['gotSeat'] = $_GET['gotSeat'];
echo '<pre>';
print_r($train);
echo '</pre>';
}
返回以下数组:
Array
(
[0] => Array
(
[trainType] => tLine
)
)
我最初假设它会返回更类似于此的内容:
Array
(
[0] => Array
(
[trainType] => 'passenger'
Array =>
(
[onTime] => true
[gotSeat] => true
)
)
)
关于我应该做些什么以达到我想要做的任何指导?我希望我的代码可以实现我想做的事情。
答案 0 :(得分:1)
此行会将trainType
设置为字符串值:
$train[0]['trainType'] = 'hello';
然后这些行实际上将用于字符替换,稍加扭曲:
$train[0]['trainType']['onTime'] = 'foo';
$train[0]['trainType']['gotSeat'] = 'bar';
onTime
和gotSeat
都会产生0
(因为您正在使用字符串),并将第一个字符替换为f
,然后{{1} }。
因此b
会返回:
print_r($train)
以下是我如何格式化这些数据:
(
[0] => Array
(
[trainType] => bello
)
)
// define our list of trains
$train = array();
// create a new train
$new = new stdClass;
$new->type = 'a';
$new->onTime = 'b';
$new->gotSeat = 'c';
// add the new train to our list
$train[] = $new;
的结果:
print_r($trains)
访问此数据:
Array
(
[0] => stdClass Object
(
[type] => a
[onTime] => b
[gotSeat] => c
)
)
答案 1 :(得分:0)
您隐式设置(或需要)<= p>的键= 0
array (
"onTime" => true,
"gotSeat" => true
)
所以你必须这样做:
if (isset($_GET['trainType']) && isset($_GET['onTime']) && isset($_GET['gotSeat'])) {
$train[0]['trainType'] = $_GET['trainType'];
$train[0][0]['onTime'] = $_GET['onTime'];
$train[0][0]['gotSeat'] = $_GET['gotSeat'];
echo '<pre>';
print_r($train);
echo '</pre>';
}
请注意,我所做的只是将代码中的错误$train[0]['trainType']['onTime']
更改为$train[0][0]['trainType']
,同样适用于gotSeat
。
或者您可以定义一个新密钥,可能是这样的:$train[0]['booking']['onTime'] = ...