Array inside Array

1

Good evening,

I'm consuming a webservice and I get the data in json with cURL. I have the data stored in the variable $ data. What I need is the following:

Let's suppose that in the $ data variable you have the following data:

$data = [ {"nome":"Edileuza","CPF":"009876543-00"}{"nome":"Cleuza","CPF":"123456789-00"} ]

So as you can see I have the CPF inside this array. I need to consume another webservice that takes the CPF and brings other information. And with this information I will have another array that I want to put inside the first array.

I can not think of a way to do this but I think I should make a foreach on the variable $ data. Below I will show you what I think would be right and if anyone can help me I will be grateful.

$ch = curl_init($link);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

$data = curl_exec($ch);

curl_close($ch);


$data = iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($data));

$data = json_decode($data, true);

Here's what I do not know what to do

foreach ($data as $key => $value) {

$cpf = $value["CPF"]

$link2 = "https://www.siteexemplo.com.br/ws/$cpf"

$ch2 = curl_init($link2);

curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, 0);

$data2 = curl_exec($ch2);

curl_close($ch2);


$data2 = iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($data2));

$data2 = json_decode($data2, true);

}

the result would be

$data2 = [ {"Endereco":"Rua 1"}]

Dai would like the Address to go to the $ data array to look like this:

$data = [ {"nome":"Edileuza","CPF":"009876543-00", "Endereco":"Rua 1"}{"nome":"Cleuza","CPF":"123456789-00", "Endereco":"Rua 2"}

Thanks in advance for the help.

    
asked by anonymous 01.08.2018 / 04:28

1 answer

0

Try to do this:

$data = '[{"nome": "Edileuza", "CPF": "009876543-00"},{"nome": "Cleuza","CPF": "123456789-00"}]';
$data = json_decode($data, true);

$novos_dados = []; //ou array(); dependendo da versao do PHP
foreach ($data as $key => $value){

    //$data2 = '[{"Endereco":"Rua 1", "Cidade" : "Minha Cidade"}]'; //buscar data2 do webservice
    $data2 = '[{"Endereco":"Rua 1"}]'; //buscar data2 do webservice

    $data2 = json_decode($data2, true);

    if($data2) {
        foreach ($data2 as $key2 => $val2) { //adiciona todos os valores de data2 caso este tenha mais de uma informação. Ex: [{"Endereco": "Rua 1", "Cidade" : "Minha Cidade"}]
            $value += $val2; //concatena os arrays - o mesmo que $value = $value + $val2;
        }
    }
    $novos_dados[] = $value;
}

echo json_encode($novos_dados);
    
04.08.2018 / 01:33