1

为什么下面的代码:

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
                )

        )

)

关于我应该做什么来实现我想要做的任何指导?我希望我的代码使我想要做的事情变得明显。

4

2 回答 2

1

此行将设置trainType为字符串值:

$train[0]['trainType'] = 'hello';

然后这些行实际上将用于字符替换,稍微有点扭曲:

$train[0]['trainType']['onTime'] = 'foo';
$train[0]['trainType']['gotSeat'] = 'bar';

两者都onTimegotSeat导致0(因为您正在使用字符串)并将第一个字符替换为fthen 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
        )

)

访问这些数据:

echo $trains[0]->type; // returns 'a'
echo $trains[0]->onTime; // returns 'b'
echo $trains[0]->gotSeat; // returns 'c'
于 2012-10-23T05:39:45.363 回答
0

您正在隐式设置(或需要)一个 key = 0 for

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']的 to $train[0][0]['trainType'],对于gotSeat.

或者你可以定义一个新的键,可能是这样的:$train[0]['booking']['onTime'] = ...

于 2012-10-23T06:07:07.657 回答