Generating valid Php Array for jSON conversion

2

Explaining a little bit about the purpose of the code: Through the query sql returns data, the only data needed is the 'id' and the name of the 'area', so two arrays are created, one to receive the 'id's and the other to receive the 'area's', after that the two arrays will be placed in only one array, the 'id' becomes the key, and the 'area' becomes the value respectively in the same order. Convert the generated array to jSON.

This is not converting the PHP array to jSON: "echo json_encode ($ c);"

Nothing appears on the screen. Apparently the array is not valid to convert. How do I perform this valid mode conversion?

            $id = 22;
            function listaAreas($conexao,$id)
            {
                $areasArray = array();
                $query = "SELECT * FROM ciencias JOIN areas on ciencias.id=areas.areaCiencia WHERE ciencias.id={$id}";
                $resultado = mysqli_query($conexao,$query);
                    while ($ciencia = mysqli_fetch_assoc($resultado))
                    {
                        array_push($areasArray, $ciencia);
                    };
                    return $areasArray;
            };


            $areasArray = listaAreas($conexao,$id);
            $arrayIds = array();
            $arrayAreas = array();
            foreach ($areasArray as $key => $value)
            {
                foreach ($value as $a => $b)
                {
                     if($a == "id")
                     {
                        array_push($arrayIds,"{$b}");
                     };

                     if($a == "area")
                     {
                        array_push($arrayAreas,"{$b}");
                     };
                };
            };

            $c = array_combine($arrayIds, $arrayAreas);
            echo json_encode($c);

If you give one:

            echo "<pre>";
            var_export($c);
            echo "</pre>";

Output:

            array (
              1 => 'Direito Administrativo',
              2 => 'Direito Ambiental',
              3 => 'Direito Civil',
              4 => 'Direito Constitucional',
              5 => 'Direito do Consumidor',
              6 => 'Direito do Trabalho',
              7 => 'Direito Empresarial',
              8 => 'Direito Internacional',
              9 => 'Direito Penal',
              10 => 'Direito Processual Civil',
              11 => 'Direito Processual do Trabalho',
              12 => 'Direito Processual Penal',
              13 => 'Direito Tributário',
              14 => 'Direitos Humanos',
              15 => 'Estatuto da Criança e do Adolescente',
              16 => 'Ética Profissional',
              17 => 'Filosofia do Direito',
            )
    
asked by anonymous 11.12.2015 / 22:28

1 answer

1

Follow your refactored code to simplify testing and eliminate possible points of failure. One of the possibilities for json_encode to fail is to receive data with non-ASCII non-UTF-8 characters:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$id = 22;
function listaAreas($conexao,$id)
{
    $areasArray = array();
    $query = "SELECT * FROM ciencias JOIN areas on ciencias.id=areas.areaCiencia WHERE ciencias.id=".$id;
    $resultado = mysqli_query($conexao,$query);
    if mysqli_errno($conexao)
    {
        die( mysqli_error($conexao) );
    }
    while ($ciencia = mysqli_fetch_assoc($resultado))
    {
        //$areasArray[$ciencia['id']] = utf8_encode( $ciencia['area'] );
        $areasArray[$ciencia['id']] = $ciencia['area'];
    };
    return $areasArray;
 };

$c = listaAreas($conexao,$id);

echo 'ARRAY<br>';
print_r( $c );
echo 'JSON<br>';
print_r( json_encode( $c ) );

If the data is not in UTF-8, adjust the line within while to that:

 $areasArray[$ciencia['id']] = utf8_encode( $ciencia['area'] );

Assuming the DB has the fields id and area , this code should work with the same result as the previous one (including with the encode working), although much leaner.

Expected result:

{
 "1":"Direito Administrativo",
 ...
 "15":"Estatuto da Crian\u00e7a e do Adolescente",
 "16":"\u00c9tica Profissional","17":"Filosofia do Direito"
}
    
11.12.2015 / 22:42