Home > database >  PHP append one array into multiple arrays
PHP append one array into multiple arrays

Time:09-09

I have a situation where one array is needed to be (appended or pushed) into multiple arrays I am testing against. My project is WordPress based, but this is a general PHP question. If I have the following setup:


    $tq_exact_matches = array('relation' => 'AND');
    $tq_any_matches = array('relation' => 'OR');

    //I WANT MY ARRAY BELOW TO ALSO BE STORED IN $tq_any_matches[], NOT JUST $tq_exact_matches[]
    //HOW CAN I DO THAT WITHOUT WRITING IT TWICE?

        $tq_exact_matches[] = array(
            'taxonomy' => 'focus-area',
            'field'    => 'name',
            'terms'    => $pluck_term_names_fa,
        );

CodePudding user response:

Use variable.

$tq_exact_matches = array( 'relation' => 'AND' );
$tq_any_matches   = array( 'relation' => 'OR' );

// I WANT MY ARRAY BELOW TO ALSO BE STORED IN $tq_any_matches[], NOT JUST $tq_exact_matches[]
// HOW CAN I DO THAT WITHOUT WRITING IT TWICE?

$extra_tax_query = array(
    'taxonomy' => 'focus-area',
    'field'    => 'name',
    'terms'    => $pluck_term_names_fa,
);

$tq_exact_matches[] = $extra_tax_query;
$tq_any_matches[]   = $extra_tax_query;

CodePudding user response:

You may do it like this

    $tq_exact_matches = array('relation' => 'AND');
$tq_any_matches = array('relation' => 'OR');

//I WANT MY ARRAY BELOW TO ALSO BE STORED IN $tq_any_matches[], NOT JUST $tq_exact_matches[]
//HOW CAN I DO THAT WITHOUT WRITING IT TWICE?

    $m = array(
        'taxonomy' => 'focus-area',
        'field'    => 'name',
        'terms'    => 'we'
    );
    
    
    list($tq_exact_matches,$tq_any_matches) = [$tq_exact_matches   $m, $tq_any_matches   $m  ];
  • Related