【问题标题】:Change Index Key to Name将索引键更改为名称
【发布时间】:2014-12-08 19:28:11
【问题描述】:

我已经构建了一个用于自定义 Wordpress 查询的多维数组。虽然是Wordpress,但我觉得这更像是一个基本的PHP问题。

我现在拥有的数组可以正确输出所有内容,接受索引值。我需要它是一个字符串而不是一个整数。

这是我需要的输出

Array (
    [post_type] => property
    [posts_per_page] => -1
    [tax_query] => Array (
        [0] => Array (
            [taxonomy] => state
            [field] => slug
            [terms] => illinois
        )
        [1] => Array (
            [taxonomy] => illinois_county
            [field] => slug
            [terms] => fulton
        )
    )
)

这是实际输出的内容

Array (
    [post_type] => property
    [posts_per_page] => -1
    [0] => Array (
        [0] => Array (
            [taxonomy] => state
            [field] => slug
            [terms] => illinois
        )
        [1] => Array (
            [taxonomy] => illinois_county
            [field] => slug
            [terms] => fulton
        )
    )
)

唯一的区别是我的第二个数组的键是0,需要是tax_query

为了获得这个数组,我声明了$tax_query_array = array();,然后根据 url 中存在的变量(例如$tax_query_array[] = $state_array;$tax_query_array[] = $county_array;)根据需要删除我的子数组。然后最后调用$tax_query_array 我需要最终的多维数组输出。

唯一阻止我的是最初的 [0] 需要改为 [tax_query]

这里是完整的代码:

$tax_query_array = array();

$tax_query_array['tax_query'][] = $state_array;
$tax_query_array['tax_query'][] = $county_array;
$tax_query_array['tax_query'][] = $price_range_array;

$taxonomy_args = array(
    'post_type' => 'property',
    'posts_per_page' => -1,
    $tax_query_array
}

通过 MikeBrant 将 $tax_query_array[] = $county_array; 更改为 $tax_query_array['tax_query'][] = $county_array; 的输出:

Array (
    [post_type] => property
    [posts_per_page] => -1
    [0] => Array (
        [tax_query] => Array (
            [0] => Array (
                [taxonomy] => state
                [field] => slug
                [terms] => illinois
            )
            [1] => Array (
                [taxonomy] => illinois_county
                [field] => slug
                [terms] => fulton
            )
        )
    )
)

【问题讨论】:

标签: php arrays wordpress multidimensional-array


【解决方案1】:

试试这个代码:

$taxonomy_args = array(
    'post_type' => 'property',
    'posts_per_page' => -1,
    'tax_query'=> array($state_array, $county_array, $price_range_array)
}

【讨论】:

  • 我觉得你需要$tax_query_array['tax_query'][] = $country_array;
  • 但是$country_array 已经是一个数组,你不需要再创建一个
  • 是的,但是看看他的结构。它在tax_query 元素内有嵌套数组。如果您采用您的方法,您将覆盖该索引处的整个元素,而不是向其追加新条目。
  • 这是真的。答案只是将索引重写为最后创建的数组。 @MikeBrant 的答案几乎可以让您在添加 tax_query 键方面到达那里,但它只是将数组嵌套更深一层,而不是将第一个键从 0 重命名为 tax_query
  • @MikeBrant 将您的输出添加到问题中
猜你喜欢
  • 2019-06-18
  • 1970-01-01
  • 1970-01-01
  • 2019-01-08
  • 1970-01-01
  • 1970-01-01
  • 2013-08-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多