Khushboo Gupta
Khushboo Gupta

Reputation: 113

Slim framework array is not encoding in JSON

I have an array I'm encoding in JSON using withJson() but it is throwing slim application error. Below is my code and array value:

            $db = Db::get_instance();
            $stmt = $db->query($sql);
            if($stmt->rowCount() > 0)
            {
                $dataList = $stmt->fetchAll(PDO::FETCH_ASSOC);
                //print_r($dataList);die;
            }
            $data = array();
            foreach($dataList as $row)
            { //print_r($row);
                $id = '';
                $name = '';
                foreach($row as $key=>$value)
            {
                if($key == 'id') $id = $value;
                if($key == 'countname') $countname = trim($value);
                if($key == 'city') $city = trim($value);
                if($key == 'region') $region = trim($value);
                if($key == 'type')
                { 
                    if($value == 'country') $name="$countname ($value)";
                    if($value == 'state') $name = "$region, $countryname ($value)";
                    if($value == 'city') $name="$city,$region,$countname ($value)";
                }
                //$name = str_replace(',',' ',$name);
                $temp['id'] = $id;
                $temp['name'] = $name;
            }
            $data[] = $temp;
        }print_r($data);die;
        return $response->withJson($data,200);

Please note there are some special characters in my array:[7] => Array ( [id] => 4634 [name] => Saint-g�rard,,Belgium (city) )

My array is below:

Array
(
    [0] => Array
        (
            [id] => 65
            [name] => Ura Vajgurore,,Albania (city)
        )

    [1] => Array
        (
            [id] => 2024
            [name] => Birregurra,,Australia (city)
        )

    [2] => Array
        (
            [id] => 2703
            [name] => Kallangur,,Australia (city)
        )

    [3] => Array
        (
            [id] => 985
            [name] => Gurnitz,,Austria (city)
        )
)

Upvotes: 1

Views: 219

Answers (1)

hitttt
hitttt

Reputation: 1189

As you mentioned that there were special characters in my array data: example:

 [7] => Array
            (
                [id] => 4634
                [name] => Saint-gÚrard,,Belgium (city)
            )

you have to reset constant name after DB connection establishment:

$db = Db::get_instance();
$db->exec("SET NAMES 'utf8';");

Hope this would work for you.

Upvotes: 2

Related Questions