Generating valid Php Array for json conversion

Asked

Viewed 434 times

2

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

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

Nothing appears on the screen. Apparently the array is not valid for converting. How to perform this conversion in a valid way?

            $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 a:

            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',
            )

1 answer

1


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

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 inside the while for that:

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

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

Expected result:

{
 "1":"Direito Administrativo",
 ...
 "15":"Estatuto da Crian\u00e7a e do Adolescente",
 "16":"\u00c9tica Profissional","17":"Filosofia do Direito"
}
  • ( ! ) Parse error: syntax error, Unexpected 'print_r' (T_STRING), expecting ',' or ';' in D: wamp www edicao carregaSelectCienciaArea.php on line 114

  • ARRAY Array ( [1] => Administrative Law [2] => Environmental Law [3] => Civil Law [4] => Constitutional Law [5] => Consumer Law [6] => Labour Law [7] => Business Law [8] => International Law [9] => Criminal Law [10] => Civil Procedural Law [11] => Labour Procedural Law [12] => Criminal Procedural Law [13] => Tax Law [14] => Human Rights [15] => Statute of Children and Adolescents [16] => Professional Ethics [17] => Philosophy of Law ) JSON

  • I forgot the ; there in echo kkk, the good thing is that we know that the error appears on the screen. Just put the ; in ECHO and see what changes, updated the answer.

  • yes appeared the array, I sent the msg a few minutes ago =)

  • $arr = array('a' => 'á' ); echo (json_encode($arr)); {"a":" u00e1"}

  • JSON {"1":"Administrative Law","2":"Environmental Law","3":"Civil Law","4":"Constitutional Law","5":"Consumer Law","6":"Labour Law","7":"Business Law","8":"International Law","9":"Criminal Law","10":"Civil Procedural Law","11":"Labour Procedural Law","12":"Criminal Procedural Law","13":"Tribut Law u00e1rio","14":"Human Rights","15":"Children’s Statute u00e7a and Adolescent Law","16":" u00c9tica Profissional","17":"Philosophy of Law"}

  • The problem really seems to be that of encoding. It generated json but changed the accented characters.

  • @user31050 is to change anyway, is to be with 0000. You can rest assured that Code does right on the other side to convert to accented characters, accent in json is always encoded. Then, if you have a little time, try to understand the simplifications I made in the rest of the code, it can help you in other situations.

  • Okay Bacco thanks so much for the help, thanks!

  • @user31050 any questions, leave a comment. And if it’s about other different parts, you can open new questions.

Show 5 more comments

Browser other questions tagged

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