Merge array as PHP

4

I have this:

$categoria_1[0] = array(
    'code' => 'ALI000001',
    'name' => 'Alimento > Arroz
);

$categoria_2[0] = array(
    'code' => 'ALI000002',
    'name' => 'Alimento > Massas
);

You have to leave it like this:

$category[0] = [{'code' => 'ALI000001', 'name' => 'Alimento > Arroz},{'code' => 'ALI000002', 'name' => 'Alimento > Massas}]

Does anyone have any tips?

    
asked by anonymous 08.04.2017 / 17:52

3 answers

2

Even using array_merge , you'll always lose one of them, the best you can do is get something like this using array_merge_recursive :

array_merge_recursive($el1, $el2);
#saida:
array([code]=>array([0]=>A..01 [1]=>A..02) [name]=>array([0]=>Al...M...s [1]=>Al...> M...s))

Because the elements of both arrays have the same index. Unless you put them in a variable as two distinct groups.

$novo= array();
array_push($novo, $el1);
array_push($novo, $el2);
#saida:
array([0]=>array([code]=>...[name]) [1]=>array([code]=>...[name]))

Or:

$novo= array();
$novo[] = $el1;
$novo[] = $el2;
#saida:
array([0]=>array([code]=>...[name]) [1]=>array([code]=>...[name]))

Another even simpler way is to use the + join operator instead of array_merge :

$novo = $el1 + $el2;

There are still other ways to do this, but your question lacks details.

    
08.04.2017 / 19:24
1
$categoria_1[0] = array(
    'code' => 'ALI000001',
    'name' => 'Alimento > Arroz'
);

$categoria_2[0] = array(
    'code' => 'ALI000002',
    'name' => 'Alimento > Massas'
);

$category[0]  = array_merge($categoria_1, $categoria_2);
    
08.04.2017 / 17:57
0

array_merge and json_encode :

$category[0] = json_encode(array_merge($categoria_1, $categoria_2));
var_dump($category[0]);

Will return:

string(94) "[{"code":"ALI000001","name":"Alimento Arroz"},{"code":"ALI000002","name":"Alimento > Massas"}]"
    
10.04.2017 / 19:04