0

I have the following structure:

  {
    "produto_id" : 54,
    "descricao_id" : 25,
    "contas" : [
        {
            "marketplace_id" : 8,
            "contas_ids" : [
                 6, 8, 9
                ]
        },
        {
            "marketplace_id" : 9,
            "contas_ids" : [
                 44, 100
                ]
        }
        ]
}

I want to get an array contained all the "contas_ids" like this:

  [6, 8, 9, 44, 100]

I've tried array_map but I had to use so many. With array_column I achieve something close but it divided the output in several arrays.

 $ids = array_column($contas,  'contas_ids');

using "dd" I get this.

   array:2 [
  0 => array:3 [
    0 => 6
    1 => 8
    2 => 9
  ]
  1 => array:2 [
    0 => 44
    1 => 100
  ]
]

Can someone help me produce a single array with all "contas_id"?

Diego Alves
  • 2,462
  • 3
  • 32
  • 65

3 Answers3

0

After you get the sub-arrays with $ids = array_column($contas, 'contas_ids');, you can combine the arrays using array_merge, as outlined in this question: Merge all sub arrays into one

call_user_func_array("array_merge", $ids);
zeterain
  • 1,140
  • 1
  • 10
  • 15
0

This should get you what you need.

$json = '{
    "produto_id" : 54,
    "descricao_id" : 25,
    "contas" : [{
        "marketplace_id" : 8,
        "contas_ids" : [ 6, 8, 9 ]
    },
    {
            "marketplace_id" : 9,
            "contas_ids" : [ 44, 100 ]
    }
    ]
}
';

$ids=[];
foreach(json_decode($json,true)['contas'] as $key => $val){
    $ids = array_merge($ids, $val['contas_ids']);
}
var_dump($ids);
Jason K
  • 1,406
  • 1
  • 12
  • 15
0

One more array_merge() solution, but this time with an obscure operator!

<?php
$json = '{
    "produto_id" : 54,
    "descricao_id" : 25,
    "contas" : [
        {
            "marketplace_id" : 8,
            "contas_ids" : [
                 6, 8, 9
                ]
        },
        {
            "marketplace_id" : 9,
            "contas_ids" : [
                 44, 100
                ]
        }
        ]
}';
$contas = json_decode($json, true);
$ids = array_column($contas["contas"], "contas_ids");
$integers = array_merge(...$ids);
print_r($integers);

Output:

Array
(
    [0] => 6
    [1] => 8
    [2] => 9
    [3] => 44
    [4] => 100
)
miken32
  • 42,008
  • 16
  • 111
  • 154