Create associative array with other PHP arrays to use as JSON return

Asked

Viewed 91 times

0

As an example, I’m going to use what I was given very simply, this Array will be obtained from data from a query of a BD:

$S1 = [[0,100], [1,200], [2,700]];
$S2 = [[0,700], [1,300], [2,400]];
$Label = [[0,SPI], [1,MVA], [2,ITB]];

I need to create a Array unique with this information to achieve a return JSON valid, but I do not understand how to do and I am unable to associate the Arrays and the attempts I made became strange, the ending was not correct.

  • Are you sure this information is correct? I don’t think this statement of these arrays is correct (I may be wrong, it’s been a while since I didn’t use php). I imagine it would look something like this: $S1 = [[0,100], [1,200], [2,700]]; ???

  • I’m experiencing syntax error in your array statements.

2 answers

1

I believe that the statements of these arrays are wrong.. so I will consider that the correct one would be this way:

$S1 = [[0,100], [1,200], [2,700]];
$S2 = [[0,700], [1,300], [2,400]];
$Label = [[0,'SPI'], [1,'MVA'], [2,'ITB']];

$arr = [
        'S1' => $S1,
        'S2' => $S2,
        'Label' => $Label
    ];

var_dump(json_encode($arr));

1


I believe this is your answer:

<?php 
    header('Content-Type: application/json');
    $S1 = [[0,100], [1,200], [2,700]];
    $S2 = [[0,700], [1,300], [2,400]];
    $Label = [[0,'SPI'], [1,'MVA'], [2,'ITB']];

    $retorno = array('S1' => $S1, 'S2' => $S2, 'Label' => $Label);
    echo json_encode($retorno);
?>
  • Hi @Christian Luã Lemos, thanks for the excellent tip, just tell me one thing, there is within the PDO the possibility or resource of language so that my query already comes formatted as in the example I mentioned. $S1 = [[0,100], [1,200], [2,700]; $S2 = [[0,700], [1,300], [2,400]; $Label = [[0,'SPI'], [1,'MVA'], [2,'ITB']];

  • According to the documentation, perhaps FETCH_ASSOC. In http://php.net/manual/en/pdostatement.fetch.php

Browser other questions tagged

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