How to join two array variables into one in php?

2

Good afternoon

I have the following code

<?php
include_once("con.php");

$pdo = conectar();

$data = file_get_contents("php://input");
$data = json_decode($data);

$idempresa = $data->idempresa;
$subcategoria = "Recebimento";

$buscaContaEntrada=$pdo->prepare('SELECT * FROM conta WHERE empresa_idempresa=:idempresa AND subcategoria=:subcategoria');
$buscaContaEntrada->bindValue('idempresa', $idempresa);
$buscaContaEntrada->bindValue('subcategoria', $subcategoria);
$buscaContaEntrada->execute();

while ($linha=$buscaContaEntrada->fetch(PDO::FETCH_ASSOC)) {

    $return[] = array(
        'idconta'   => $linha['idconta'],
        'conta' => utf8_encode($linha['conta']),
        'idsubcategoria'    => utf8_encode($linha['subcategoria_idsubcategoria']),
    );
}

echo json_encode($return);
?>

But I need to get the data idsubcategory, make another select, in the database, and the result, play within $ return ... How can I do this?

    
asked by anonymous 18.01.2017 / 20:58

3 answers

1

Dude, take that first bracket out

$return[] = array(

Turns

$return = array(

Because this way you are creating 2 levels of array (return [0] [data]) and when you read in js is giving object because in fact it is object itself.

To simply join two arrays is array_merge, but my answer there solves what you want

    
19.01.2017 / 02:13
1

To join 2 arrays to 1 you can use the function array_merge , example:

<?php
$array1 = array("cor" => "vermelho", 2, 4);
$array2 = array("a", "b", "cor" => "verde", "forma" => "trapezoide", 4);
$result = array_merge($array1, $array2);
echo json_encode($result);
?>
//saida
{"cor":"verde","0":2,"1":4,"2":"a","3":"b","forma":"trapezoide","4":4}
    
18.01.2017 / 22:48
0

Create a function that fetches the data from the CategoryID and then adds the return from it to your array.

while ($linha=$buscaContaEntrada->fetch(PDO::FETCH_ASSOC)) {
    $novaVariavelParaInserirNoArray = buscarInformacoesNoBanco($linha['subcategoria_idsubcategoria']);//funcao que realiza sua busca.
    $return[] = array(
        'idconta'   => $linha['idconta'],
        'conta' => utf8_encode($linha['conta']),
        'idsubcategoria'    => utf8_encode($linha['subcategoria_idsubcategoria']),
        'informacoesTrazidasDoBanco' => $novaVariavelParaInserirNoArray
    );
}

I think this should be enough.

    
18.01.2017 / 21:07