Return an array of Objects with PHP

0

I have the following code in PHP:

$output = '';

$output .= 'values: [{ ';

$output .= 'arg: "N", ';
$output .= 'val1: '.round($Val1N / $rowCount,2).', '; 
$output .= 'val2: '.round($Val2N / $rowCount,2).', ';
$output .= 'val3: '.round($Val3N / $rowCount,2).', ';
$output .= 'val4: '.round($Val4N / $rowCount,2).', ';
$output .= 'val5: '.round($Val5N / $rowCount,2).', ';
$output .= 'val6: '.round($Val6N / $rowCount,2).', ';
$output .= 'val7: '.round($Val7N / $rowCount,2).', ';
$output .= 'val8: '.round($Val8N / $rowCount,2).' }, {';

$output .= 'arg: "NNE", ';
$output .= 'val1: '.round($Val1NNE / $rowCount,2).', '; 
$output .= 'val2: '.round($Val2NNE / $rowCount,2).', ';
$output .= 'val3: '.round($Val3NNE / $rowCount,2).', ';
$output .= 'val4: '.round($Val4NNE / $rowCount,2).', ';
$output .= 'val5: '.round($Val5NNE / $rowCount,2).', ';
$output .= 'val6: '.round($Val6NNE / $rowCount,2).', ';
$output .= 'val7: '.round($Val7NNE / $rowCount,2).', ';
$output .= 'val8: '.round($Val8NNE / $rowCount,2).' }]';

echo json_encode($output);

That generates me previously calculated values, until here everything is correct, the problem comes when returning this array of objects with echo, I use ajax with the following code:

       $.ajax({
          url:'process.php',
          method:"POST",
          data:{a:a, b:b, c:c},
           success:function(data)
          {
            var response = JSON.parse(data);
            funcion_cargar(response);

The problem comes when I return the values but using console.info (response) it seems that in String format, in any case not in the way I need them. It works correctly if I create a variable on the main page in the following way:

var response = 
[{values: 
[{arg: "N",
val1: 0, 
val2: 0.01,
val3: 0,
val4: 0,
val5: 0,
val6: 0,
val7:0,
val8: 0}, {
arg: "NNE",
val1: 0,
val2: 0.01,
val3: 0,
val4: 0,
val5: 0,
val6: 0,
val7: 0,
val8: 0
}]}];

Say that the function that uses the values on the main page uses the values in this way

   funcion_cargar(response){
    ...
    dataSource: response[0].values,
    ...
   }
    
asked by F.Sola 27.04.2018 в 14:22
source

1 answer

4

You are generating a json string, which you then encode to json. That is not what you want. What you are interested in is creating an array, and then coding it to json.

You could try something like:

$output = [];
$output['values'][] = [
  'arg' => 'N',
  'val1' => round($Val1N / $rowCount, 2),
  'val2' => round($val2N / $rowCount, 2),
];

$oputput['values'][] = [
  'arg' => 'NNE',
  'val1' => round($Val1NNE / $rowCount, 2),
  'val2' => round($val2NNE / $rowCount, 2),
];

That's an output object, with a VALUES tag that contains an array of elements.

and now yes, that you can send as a json:

echo json_encode($output, true);
    
answered by 27.04.2018 / 14:29
source