0

我有一个问题,我什至不知道如何描述。我需要构建一个动态数组,并将其包含在另一个数组中。让我展开。这是我的代码:

$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'
),

如果我把它代替代码中的变量,效果很好。因此,该变量没有格式错误,只是没有在另一个数组中解析。也许我是个白痴,这是不可能的?我究竟做错了什么?!?!?!这让我发疯,我什至不知道如何用短语搜索解决方案。

4

2 回答 2

2

您正在生成一个字符串,而不是一个数组。

$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
);
于 2013-04-05T21:33:33.560 回答
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通常被认为是邪恶的。

于 2013-04-05T21:32:57.853 回答