我遇到了一个我甚至不知道如何描述的问题。我需要构建一个动态数组,并将其包含在另一个数组中。让我扩大。这是我的代码:
$myarrayarray = '';
$categoriesTerms = $catlist = rtrim($categoriesTerms,',');
$categoriestocheck = explode(',',$categoriesTerms);
foreach($categoriestocheck as $key=>$value){
$myarrayarray .= "array(";
$myarrayarray .= "'taxonomy' => 'map_location_categories',";
$myarrayarray .= "'terms' => array(".$value."),";
$myarrayarray .= "'field' => 'slug',";
$myarrayarray .= "'operator' => 'AND'";
$myarrayarray .= "),";
}
$myarrayarray .= "array(";
$myarrayarray .= "'taxonomy' => 'map_location_categories',";
$myarrayarray .= "'terms' => array('event'),";
$myarrayarray .= "'field' => 'slug',";
$myarrayarray .= "'operator' => 'OR'";
$myarrayarray .= "),";
echo $myarrayarray;
$locationArgs = array(
'post_type' => 'maplist',
'orderby' => $orderby,
'order' => $orderdir,
'numberposts' => -1,
'tax_query' => array($myarrayarray),
);
$mapLocations = get_posts($locationArgs);
这不会产生错误,它只是无法以任何方式限制数据返回。如果我打印我的$ myarrayarray变量,我会得到一个结合油漆和加压气缸的搜索:
array(
'taxonomy' => 'map_location_categories',
'terms' => array('paint'),
'field' => 'slug',
'operator' => 'AND'
),
array(
'taxonomy' => 'map_location_categories',
'terms' => array('pressurized-cylinders'),
'field' => 'slug',
'operator' => 'AND'
),
array(
'taxonomy' => 'map_location_categories',
'terms' => array('event'),
'field' => 'slug',
'operator' => 'OR'
),
如果我把它放在代码中的变量的位置,它的效果很好。因此,变量没有格式错误,它只是没有在另一个数组中解析。也许我是个白痴,这是不可能的?我究竟做错了什么?!?!?!这让我感到疯狂,我甚至不知道如何用词来搜索解决方案。
答案 0 :(得分:2)
您正在生成STRING,而不是数组。
$str = 'hello,there';
$arr = array($str);
不会产生
$arr = array(
'hello', // element #1
'there' // element #2
);
它产生
$arr = array(
'hello,there' // single element #1
);
如果要生成嵌套数组,则跳过整个字符串业务
$data = array();
foreach($categoriestocheck as $key=>$value){
$data[] = array(
'taxonomy' => 'map_location_categories',
'terms' => array($value.),
etc..
);
}
$locationArgs = array(
...
data => $data
);
答案 1 :(得分:1)
试试这个:
$myarrayarray = array();
$categoriesTerms = $catlist = rtrim($categoriesTerms,',');
$categoriestocheck = explode(',',$categoriesTerms);
foreach($categoriestocheck as $key=>$value) {
$tmp = array();
$tmp['taxonomy'] = 'map_location_categories';
$tmp['terms'] = array($value);
$tmp['field'] = 'slug';
$tmp['operator'] = 'AND';
$myarrayarray []= $tmp;
}
$tmp = array();
$tmp['taxonomy'] = 'map_location_categories';
$tmp['terms'] = array('event');
$tmp['field'] = 'slug';
$tmp['operator'] = 'OR';
$myarrayarray []= $tmp;
print_r($myarrayarray);
或者使用eval($myarrayarray)
,但请注意eval
的使用通常被视为邪恶。