当在数组中使用存储在变量中的数组时,停止parent [0]

时间:2017-07-26 11:28:09

标签: php arrays

下面的代码以这种方式输出数组:

Screenshot

我们不希望该部分以红色突出显示,我们如何删除它?

{{1}}

4 个答案:

答案 0 :(得分: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:

答案 1 :(得分: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;

?>

答案 2 :(得分:0)

splat operator添加到Alive 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的数组计数,此方法很有用。

答案 3 :(得分: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
                )    
        )    
)