PHP foreach不按预期运行

时间:2014-09-13 13:53:05

标签: php arrays

我有一个名为“观察”的数组(从Python应用程序发布)。它看起来像这样:

Array
(
[0] => Array
    (
        ['remote_id'] => 1
        ['dimension_id'] => 1
        ['metric'] => 1
    )

[1] => Array
    (
        ['remote_id'] => 1
        ['dimension'] => 2
        ['metric'] => 2
    )

[2] => Array
    (
        ['remote_id'] => 1
        ['dimension_id'] => 3
        ['metric'] => 3
    )
 (etc)

我想遍历所有remote_id,dimension_id和metric的实例,并将它们写入数据库。但我无法访问它们 - 这是我的PHP:

foreach ($_POST["observations"] as $observation) {
echo "Let's try and access the whole array... \n";
print_r ($observation);
echo "But what about the sub elements? \n";
print_r ($observation[0]);
print_r ($observation['dimension_id']);
}

返回:

Let's try and access the whole array... 
Array
(
    ['remote_id'] => 1
    ['dimension_id'] => 1
    ['metric'] => 1
)
But what about the sub elements? 
Let's try and access the whole array... 
Array
(
    ['remote_id'] => 1
    ['dimension'] => 2
    ['metric'] => 2
)
But what about the sub elements? 
(etc)

所以我的print_r($ observation [0])和print_r($ observation ['dimension_id'])都无法访问相应的子元素并返回空。我在这里缺少什么?

编辑:关于我(可能是格式错误的)POST的一些问题。像这样在Python中执行:

data = urllib.urlencode([
       ("observations[0]['remote_id']", 1),
       ("observations[0]['dimension_id']", 1),
       ("observations[0]['metric']",metric1),

       ("observations[1]['remote_id']", 1),
       ("observations[1]['dimension']", 2),
       ("observations[1]['metric']", metric2),

       ("observations[2]['remote_id']", 1),
       ("observations[2]['dimension_id']", 3),
       ("observations[2]['metric']",metric3),

       ("observations[3]['remote_id']", 1),
       ("observations[3]['dimension_id']", 4),
       ("observations[3]['metric']",metric4),

       ("observations[4]['remote_id']", 1),
       ("observations[4]['dimension_id']", 5),
       ("observations[4]['metric']",metric5),
    ])
    response = urllib2.urlopen(url=url, data=data)

1 个答案:

答案 0 :(得分:1)

根据你给定的数组工作:

$array = Array(
        0 => Array
        (
            'remote_id' => 1,
            'dimension_id' => 1,
            'metric' => 1
        ),
        1 => Array
            (
                'remote_id' => 1,
                'dimension_id' => 2,
                'metric' => 2
            ),
        2 => Array
            (
                'remote_id' => 1,
                'dimension_id' => 3,
                'metric' => 3
            )
);  
foreach ($array as $observation) {

    echo "Remote id: ". $observation['remote_id']."<br />";
    echo "Dimension id: ". $observation['remote_id']."<br />";
    echo "Metric: ". $observation['metric']."<br />";
}

那将打印:

Remote id: 1
Dimension id: 1
Metric: 1
Remote id: 1
Dimension id: 1
Metric: 2
Remote id: 1
Dimension id: 1
Metric: 3

但看起来您的$_POST["observations"]不是$observation的数组,只有一个$observation

您的表单可能有问题。你在输入中使用了数组吗? <input type="text" name="observations[0]['metric']" />