2

I would like to group several (n) tables into a single large table. Exemple :

$tab1 = array("test0","test1");
$tab2 = array("test2","test3");
$tab3 = array("tes..","....");

But for example with 10 tables. Instead of writing

$result = array_merge($tab1, $tab2, $tab3 --> $tab10);

The algorithm should do this on its own, but I admit I'm lost. I thought I would do it recursively.

If anyone would have how to do it, thanks

2
  • So do you know how many and/or what these Arrays (not tables) are called before trying to merge them all into one? Commented Sep 2, 2020 at 11:11
  • To me it looks like her array( [0] => array([0]=>[0]="test"[1]= test2") array[1] => array([0] =>"test3" [1] => "test4" and this for 10 array. and I would like it to be array[0]=test1 [2] = test2 [3] = test3 ...... In one big array Commented Sep 2, 2020 at 11:24

4 Answers 4

3

I would start by not-using numerical variable names: Instead I use an array:

<?php
$tab[] = array("test0","test1");
$tab[] = array("test2","test3");
$tab[] = array("test4","test3");
?>

Next: you can loop through them to merge

<?php 
$result = array();
for($i=0;$i<count($tab);$i++) {
   $result = array_merge($result, $tab[i]);
 }  
 ?>
Sign up to request clarification or add additional context in comments.

2 Comments

You don't need the loop, just use ...$tab.
or use the foreach-loop. I use "For", as my first example needed it so. The ...$tab is even nicer. But from which PHP version will it work? Edit: PHP 5.6 (quite some time)
3

Using array_merge() with all of the arrays in one main array can be simplified using the argument unpacking (or splat operator) ......

$tab[] = array("test0","test1");
$tab[] = array("test2","test3");
$tab[] = array("test4","test3");

print_r(array_merge(...$tab));

Comments

0

Don't introduce variables which you don't "use":

$tables = [];
$tables[] = ["test0", "test1"];
$tables[] = ["test2", "test3"];
$tables[] = ["tes..", "...."];
$mergedTables = [];
foreach ($tables as $table) {
    $mergedTables = array_merge($tables, $table);
}

Comments

0

One thing comes to mind, it's not the prettiest, but it works. Without changing your array names.

It checks for $$tab, which is basically a variable starting with 'tab' and ending with our incremented $i. Then it merges them one by one.

<?php

$tab1 = array("test0", "test1");
$tab2 = array("test2", "test3");
$tab3 = array("tes..", "....");

$i = 1;

$tab = 'tab' . $i;

$data = [];

while (isset($$tab)) {
    $data = array_merge($data, $$tab);
    $i++;
    $tab = 'tab' . $i;
}

print_r($data);

This is the output:

Array ( [0] => test0 [1] => test1 [2] => test2 [3] => test3 [4] => tes.. [5] => .... )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.