Foreach只返回数组元素的第一个字母?

时间:2012-03-27 01:47:17

标签: php arrays oop foreach

There is almost identical question,但我不知道该怎么办。

我刚开始使用OO PHP,我在班上有这个功能:

public function show() {
    foreach($this->data['fields'] as $field) {
        $type = $field['type'];
        echo $type;
    }
}

这是输入数据:

my_function('id', 
    array(
    'foo' => 'bar',
    'bar' => 'foo',
    'fields' => array(
        'type' => 'my_type',
        'foo' => 'bar',
        'etc.' => 'value'),
    ),
);

当然echo $field['type']只返回my_typem)的第一个字母。

我不能简单地使用echo $field,因为我在此数组下有多个键,它返回my_typebarvalue而不是my_type$field[0]也是如此( mbv)。我该怎么办?

4 个答案:

答案 0 :(得分:2)

$this->data['fields']中有三个键值对:type => my_typefoo => baretc. => value。当您使用此foreach语法时,$field将仅包含 对的值,该值始终为字符串。

索引运算符(变量后的括号,如$foo['bar'])也适用于字符串,并返回给定索引处的字符。类型juggling将字符串'type'转换为整数0,因此您将获得字符串的第一个字符。

我不确定你想要什么,实际上,如果echo $field不合适的话。除非被问到,否则PHP不会打印换行符或分隔符,因此您可能需要尝试echo $field . ' '并查看值实际上是不同的。

答案 1 :(得分:2)

当您遍历以下字段时:

array(
   'type' => 'my_type',
   'foo' => 'bar',
   'etc.' => 'value'
)
使用

foreach($this->data['fields'] as $field) 

在每次迭代中,$field已经是你正在寻找的值(my_type,bar,value),所以正如@zneak所提到的那样做$ field ['type']会得到php to juggle'类型'到0,因此你得到第一个角色。

要在键入键时获取值,您可以执行以下操作:

public function show() {
    foreach($this->data['fields'] as $key => $field) {
        if($key == 'type') echo $field;
    }
}

答案 2 :(得分:1)

foreach遍历$data['fields'] 中的所有元素。在第一次迭代中,$field将为"my_type",在第二次迭代$field将为"bar",依此类推。即,在每次迭代中,$field将是一个字符串,而不是一个数组。

您需要一个适合该循环的数组数组,例如:

'fields' => array(
    array(
        'type' => 'my_type',
        'foo' => 'bar',
        'etc.' => 'value',
    ),
    ...
)

答案 3 :(得分:0)

您的数组'字段'如下:

    $fields['type'] = 'my_type';
    $fields['foo'] = 'bar';
    $fields['etc'] = 'value';

意味着您的数组只有一个维度。 所以像上面那样访问它。
在foreach中,你告诉php通过键(类型,foo,等)。所以$ field已经是(my_type,bar,value)!

// You either need to write:
foreach($this->data as $field) {
    $type = $field['fields']['type'];
    echo $type;
}

// Or
foreach($this->data['fields'] as $field) {
if ($field == 'type') {
        $type = $field;
        echo $type;
}
}

// Or
foreach($this->data['fields'] as $key => $val) {
if ($key == 'type') {
        $type = $val;
        echo $type;
}
}