2017-07-26 43 views
0

下面的代碼的陣列輸出以這種方式被用於:停止父[0]時存儲在變量中的陣列中的陣列

Screenshot

我們不希望的部分以紅色突出顯示,我們如何消除這一點?

<?php 

$test = array(); 

$test2[] = array(
    'key1' => '111', 
    'key2' => '111', 
    'key3' => '111', 
); 

$test2[] = array(
    'key1' => '222', 
    'key2' => '222', 
    'key3' => '222', 
); 

$test['tax_query'] = array(
    'relation' => 'AND', 
    $test2, 
); 

print_r($test); 

?> 
+0

0是元素的索引。數組中的所有元素都有索引。 – memo

+0

0是指數值,如果您不需要像您在圖片中所說的那樣,您可以使用'$ test ['tax_query'] = array( 'relation'=>'AND', 「data」=> $ test2 );' –

+0

我認爲你正在試圖做這樣的事情$ test ['tax_query'] = array( 'relation'=>'AND', 'meta_query'=> $ test2, ); –

回答

0

array_merge()或聯盟運營商將做好這項工作,沒有什麼太棘手。

代碼:(Demo

$test = array(); 

$test2[] = array(
    'key1' => '111', 
    'key2' => '111', 
    'key3' => '111', 
); 

$test2[] = array(
    'key1' => '222', 
    'key2' => '222', 
    'key3' => '222', 
); 

$test['tax_query']=array_merge(['relation'=>'AND'],$test2); // array_merge 
//$test['tax_query']=['relation'=>'AND']+$test2; // array Union operator 

print_r($test); 

輸出:

Array 
(
    [tax_query] => Array 
     (
      [relation] => AND 
      [0] => Array 
       (
        [key1] => 111 
        [key2] => 111 
        [key3] => 111 
       )  
      [1] => Array 
       (
        [key1] => 222 
        [key2] => 222 
        [key3] => 222 
       )  
     )  
) 
1

$test2上循環並將其追加到主陣列。

更新代碼:

<?php 
$test = array(); 
$test2[] = array(
    'key1' => '111', 
    'key2' => '111', 
    'key3' => '111', 
); 

$test2[] = array(
    'key1' => '222', 
    'key2' => '222', 
    'key3' => '222', 
); 
$test['tax_query'] = array(
    'relation' => 'AND', 
// $test2, 
); 
if (! empty($test2)) { 
foreach ($test2 as $testArr) { 
    $test['tax_query'][] = $testArr; 
} 
} 
print_r($test); 
?> 

Demo:

0

試試這個

<?php 

$test = array(); 

$test2[] = array(
    'key1' => '111', 
    'key2' => '111', 
    'key3' => '111', 
); 

$test2[] = array(
    'key1' => '222', 
    'key2' => '222', 
    'key3' => '222', 
); 

$test['tax_query'] = array(
    'relation' => 'AND', 
    $test2, 
); 

$finalStr = str_replace("","[0] => Array",print_r($test,true),1); 

echo $finalStr; 

?> 
0

添加splat operatorAlive To Die's answer將幫助你解開動態數組(如果您使用的PHP版本5.6和以上)

DEMO

<?php 

$test = array(); 

$test2[] = array(
    'key1' => '111', 
    'key2' => '111', 
    'key3' => '111', 
); 

$test2[] = array(
    'key1' => '222', 
    'key2' => '222', 
    'key3' => '222', 
); 

$test['tax_query'] = array(
    'relation' => 'AND' 
); 

array_push($test['tax_query'], ...$test2); // Unpack and add to array with array_push 

print_r($test); 

這種方法是有幫助的,如果你不能確定$test2的數組數。