【问题标题】:Pass variable to array index将变量传递给数组索引
【发布时间】:2013-01-27 05:06:22
【问题描述】:

这就是我所拥有的

foreach ( $post_formats as $format ) {
    if ( $options['show_post_formats'][$format] == 0 ) {
        $format = 'post-format-' . $format;
        array_push( $hide, $format );
    }
}

它工作正常......但在我调试时给了我一个未定义的索引:错误,因为它希望 $format 的值用引号引起来。我该如何正确地做到这一点?

【问题讨论】:

  • 我们需要查看更多代码
  • 好的,但是 $format 是调试器遇到的问题,因为它期望值在引号中
  • 正如@MathieuImbert 所说,更多来源会很有用,但您可以使用isset检查索引是否存在
  • @byronyasgur 您的数组中不存在特定的$format,您应该使用劳伦斯的答案。
  • 认为我可能对问题所在有错误的认识

标签: php arrays debugging multidimensional-array indexing


【解决方案1】:

由于您不确定索引是否存在,您只需使用 !empty() 并检查数组键是否存在。

<?php 
foreach ( $post_formats as $format ) {
    if (!empty($format) && array_key_exists($format, $options['show_post_formats']) && $options['show_post_formats'][$format] == 0 ) {
        $format = 'post-format-' . $format;
        array_push( $hide, $format );
    }
}
?>

【讨论】:

  • 不确定我是否理解...我是否将整个 foreach 都放入其中?
  • 我回答时没有 foreach,无论如何$format 可能是空值或空白,从而导致问题。更新
猜你喜欢
  • 2013-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-28
  • 2019-12-31
  • 2013-03-05
  • 2020-12-11
相关资源
最近更新 更多