foreach循环使用$ this作为键和值

时间:2014-06-24 09:39:41

标签: php

我想像这样做一个foreach循环

foreach ($this->data['array'] as $this->data['key'] => $this->data['value'])
{
    echo $this->data['value'];
}

然而,永远不会创建$this->data['value']。为什么这样,我做错了什么?

3 个答案:

答案 0 :(得分:1)

如果:

class YourClass {

   private data = array(
     'array' => array(
         'key1' => 'val1',
         'key2' => 'val2', etc.
      )
   );

然后它应该是:

foreach ($this->data['array'] as $key => $val)
{
    echo $val;
   // if you want to add keys and vals to data array:
   $this->data[$key] = $val;
}

答案 1 :(得分:1)

我认为$this用于当前类对象引用而不是数组

foreach ($this->data['array'] as $k => $v)
{
    echo $v;
    $this->data['key'][] = $k;
    $this->data['value'][] = $v;
}
print_r($this->data['key']);
print_r($this->data['value']);

答案 2 :(得分:1)

根据我的理解,你有一个类,其中有一个变量或数组名称$ data。

现在,您在$ data中添加了一个名为'array'的索引,对吧? 如果是这样,此代码将正常工作 -

class myClass{
    public $data = array(); //$data is an array

    function print_array(){
     foreach ($this->data['array'] as $this->data['key'] => $this->data['value'])
        {
            echo $this->data['value'];
        }   
    }
}

$ob = new myClass(); // object declaration for your class
array_push($ob->data,'array'); // added a value to the $data array.
$ob->data['array'] = array(); // the newly added value is declared as an index of an array
// Now simply push values to the array named $data['array']
array_push($ob->data['array'],1);
array_push($ob->data['array'],2);
array_push($ob->data['array'],3);

$ob->print_array(); // call the print_array() function. $this will be passed to that function

希望这有助于理解。 如果您还有问题,请发表评论。 要清楚了解,您可以访问this链接。解释了许多简单而有趣的例子!

快乐的编码!