0

I am having a array like so and I am looping trough it like this:

$options = array();
$options[0] = 'test1';
$options[1] = 'test2';
$options[2] = 'test3';

foreach($options as $x)
{
  echo "Value=" . $x ;
  echo "<br>";
}

It outputs as expected:

Value=test
Value=test2
Value=test3

Now I want to add some options to my array and loop trough them:

$options = array();
$options['first_option'] = 'test';
$options['second_option'] = get_option('second_option');
$options['third_option'] = get_option('third_option');

foreach($options as $x)
{
  echo "Value=" . $x ;
  echo "<br>";
}

But it does not work as I want. Because it outputs:

Value=first_option
Value=second_option
Value=third_option

So now I do not know how to access stored values using foreach from these guys? Something like:

Value=first_option='test'

So when I use print_r($options)
Output is:

Array
(
[first_options] => test
[second_option] => 
[third_option] => 
)
1
4

2 回答 2

4

你的循环应该是这样的:

foreach($options as $key => $val){
  echo "Val: ".$val;
  echo "<br/>";
}
于 2013-09-02T17:33:55.213 回答
1

您的代码按预期工作并产生所需的结果。你必须有其他东西改变$options. 更正:现在我看到您的编辑,您的函数没有返回任何值,因此选项 1 和 2 为空白。确保该函数返回一些东西。除此之外,所有这些代码都很好。

顺便说一句,我推荐这个:

$options = [
  'first_option' => 'test',
  'second_option' => get_option('second_option'),
  'third_option' => get_option('third_option')
];

foreach($options as $key) {
  echo "Value = {$key}<br>";
}

您还可以使用:

foreach($options as $key => $value) {
  echo "Value - {$value} = {$key}<br>";
}

或者你至少可以array()用 just替换[]。这些只是一些整洁的建议。

于 2013-09-02T17:39:39.450 回答