【问题标题】:in_array based if/then/else statement基于 in_array 的 if/then/else 语句
【发布时间】:2013-09-09 20:35:35
【问题描述】:

我希望在 in_array 语句中创建一个条件。基本上,我希望为 Wordpress 输出的数组中的每个键返回一个值(在 div 标签内)。本质上,Wordpress 根据后台管理后台的复选框对话框从这个数组中输出键。因此,如果未找到数组中的某个键(因为管理员没有在后端的复选框中单击它),那么它将根本不会显示它。

这是我能确定的最接近的代码。我决定出于测试目的,如果数组中的键不存在,我将暂时返回“Nope”字样(而不是上面段落中提到的“根本不显示它”)。

$my_arr = get_custom_field('product_options');
$opts = array(
'Option 1' => '<div>Option 1 description</div>',
'Option 2' => '<div>Option 2 description</div>',
'Option 3' => '<div>Option 3 description</div>',
);

foreach($opts as $k=>$v) {
if (in_array($my_arr[$k],$opts)!==TRUE)  echo $v; else echo 'nope'; 
}
?>   

上面的代码已经过测试,它确实为所有内容显示“选项__描述”。 It even displays "Option 2 description" when Option is not actually being outputted within the array (based off of the admin not clicking Option 2 within the backend).这是不正确的,我希望得到它(在这种情况下是为了便于测试)上述语句的“else”部分中的回声。

更新 2:当前代码在这里:http://codepad.org/nxzFUMMn

更新:当前代码在这里:http://codepad.org/iXVbmLGL

【问题讨论】:

  • $my_arr 长什么样子?
  • @tandu 我在 $my_arr 上做了一个 var_export。另外,请注意原始帖子中的更新 2,因为代码已更改。我快到了! var_export 输出:数组 ( 0 => '选项 1', 1 => '选项 3', )

标签: php arrays if-statement


【解决方案1】:

这里的技巧是切换数组,例如

<?php
$my_arr = get_custom_field('othermulti');

$opts = array(
    'Man' => '<div>Man description</div>',
    'Bear' => '<div>Bear description</div>',
    'Pig' => '<div>Pig description</div>',
);

$opts_arr = array_keys($opts);

if ( is_array($my_arr) ) {
    foreach($opts_arr as $opt) {
       if ( in_array($opt, $my_arr) ) {
          print $opts[$opt]; // will print the description for checked items.
       }
       else {
         print $opt . ' was not checked.';
       }
    }
}
else {
    print 'No options checked.';
}
?>

get_custom_field() 是使用它的插件的自定义模板函数。有关详细信息,请参阅以下链接: http://wordpress.org/support/topic/ifelse-statement-for-custom-checkbox?replies=16

【讨论】:

    【解决方案2】:

    所发生的事情表明事实上$my_arr 的值都不匹配$opts 的值。我想你想使用

    if (in_array($my_arr[$k], array_keys($opts)) !== TRUE) {
    

    还要注意$my_arr[$k] === $vin_array($x, $y) !== TRUE === !in_array($x, $y)

    【讨论】:

    • 好的。按照你的建议尝试了,但仍然没有结果:$my_arr = get_custom_field('product_options');$opts = array('Option 1' =&gt; '&lt;div&gt;Option 1 description&lt;/div&gt;','Option 2' =&gt; '&lt;div&gt;Option 2 description&lt;/div&gt;','Option 3' =&gt; '&lt;div&gt;Option 3 description&lt;/div&gt;',);foreach($opts as $k=&gt;$v) {foreach($opts as $k=&gt;$v) {if (in_array($my_arr[$k], array_keys($opts)) !== TRUE) echo $v; else echo 'nope';`}`?&gt;
    • 你需要回答 $my_arr 看起来真正得到帮助的样子
    • 查看我刚刚粘贴的代码。同样,$my_arr 是“get_custom_field('product_options');”的 Wordpress 请求
    • @cwallenpoole 好吧, opts 也被赋予等于一个数组。 $opts = array (
    • 我不知道“get_custom_field() 的 Wordpress 请求”是什么意思。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-02
    • 2011-05-11
    相关资源
    最近更新 更多