Merge array as PHP

Asked

Viewed 88 times

4

I have it:

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

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

And I need to leave it at that:

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

Does anyone have any tips?

  • Using array_merge($categoria_1, $categoria_2) works... But if one of the initial arrays is NULL, it won’t.. Any hint...

  • Try casting to see if it goes: array_merge((array)$categoria_1, (array)$categoria_2)

3 answers

2

Even using the array_merge, you’ll always lose one of them, the best you can do is get something like this using the 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 into 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 else:

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

Another even simpler way is by using the union operator + instead of the array_merge:

$novo = $el1 + $el2;

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

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);

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"}]"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.