构建一个php数组

时间:2015-10-07 17:36:35

标签: php arrays wordpress

我想要的结果:

Array (
    [search] => *stev*
    [meta_query] => Array (
        [relation] => OR
        [0] => Array (
            [key] => category
            [value] => Accounting
            [compare] => LIKE
        )
        [1] => Array (
            [key] => category
            [value] => Appraisal
            [compare] => LIKE
        )
    )
)

我得到的结果:

Array (
    [search] => *stev*
    [0] => Array (
        [meta_query] => Array (
            [relation] => OR
            [0] => Array (
                [0] => Array (
                    [key] => category
                    [value] => Accounting
                    [compare] => LIKE
                )
                [1] => Array (
                    [key] => category
                    [value] => Appraisal
                    [compare] => LIKE
                )
            )
        )
    )
)

我使用的代码:

$constArray =array();
      foreach($filter as $item){
        array_push($constArray,array('key'=>'category','value'=>$item,'compare'=>'LIKE'));
      }
      $filterArray=array('meta_query' =>array('relation'=>'OR',$constArray));
array( 
        'search' => '*' . $search . '*' ,$filterArray
      )

如何摆脱额外的数组指针?

最终解决方案

    $filterArray = array('relation' => 'OR');
    foreach ($filter as $item) {
        array_push($filterArray, array(
            'key' => 'category', 
            'value' => $item, 
            'compare' => 'LIKE'
        ));
    }
    array( 
        'search' =>  '*' . $search . '*' ,
        'meta_query' => $filterArray
      )

1 个答案:

答案 0 :(得分:1)

您忘记设置数组键,请尝试以下操作:

$final = array(
    'search' => '*stev*',
    'meta_query' => array(
        'relation' => 'OR',
        "conditions" => array()
    )
);

$filter = array("Accounting", "Appraisal");
foreach ($filter as $item) {
    $final['meta_query']['conditions'][] = array(
        'key' => 'category',
        'value' => $item,
        'compare' => 'LIKE'
    );
}

var_dump($final);

<强>结果:

array (size=2)
  'search' => string '*stev*' (length=6)
  'meta_query' => 
    array (size=2)
      'relation' => string 'OR' (length=2)
      'conditions' => 
        array (size=2)
          0 => 
            array (size=3)
              'key' => string 'category' (length=8)
              'value' => string 'Accounting' (length=10)
              'compare' => string 'LIKE' (length=4)
          1 => 
            array (size=3)
              'key' => string 'category' (length=8)
              'value' => string 'Appraisal' (length=9)
              'compare' => string 'LIKE' (length=4)