public function generateHeritageJson($query, $sexe) { $results = Parent::getSelect($query)->fetchAll(PDO::FETCH_ASSOC); $sexs = explode(",", $sexe); $collection = array(); foreach ($sexs as $sex) { $collection[$sex] = array(); } // $collection = array("man" => array(), "woman" => array()); if (!empty($results)) { foreach ($results as $row) { $sex = $row['sex']; $age = $row['age']; $country = $row['country']; $size = $row['num']; if (array_key_exists($age, $collection[$sex])) { $collection[$sex][$age][$country] = $size; } else { $addCouSize = array($country => $size); $collection[$sex][$age] = $addCouSize; } } // create the heritage Json $data = '{"name":"data", "children":['; if ($collection) { foreach ($collection as $sex => $sex_value) { $data = $data . '{"name":"' . $sex . '","children":['; foreach ($sex_value as $age => $age_value) { $data = $data . '{"name":"' . $age . '","children":['; foreach ($age_value as $country => $country_value) { $data = $data . '{"name":"' . $country . '","size":' . $country_value . '},'; } $data = substr($data, 0, -1) . ']},'; } $data = substr($data, 0, -1) . ']},'; } $data = substr($data, 0, -1) . ']}'; echo json_encode($data); } } else { echo null; } }