\s*(.*?)\s*\s*\s*(.*?)\s*\s*\s*(.*?)\s*\s*\s*(.*?)\s*|", $table, $matches, PREG_PATTERN_ORDER); unset($matches[0]); for($j = 0 ; $j < count($matches[2]); $j++) { $key = html_entity_decode($matches[2][$j]); $productKey = html_entity_decode($matches[1][$j]); $categories[$key][$productKey][] = [ "product" => html_entity_decode($matches[1][$j]), "price" => html_entity_decode($matches[3][$j]), "currency" => html_entity_decode($matches[4][$j]) ]; } ksort($categories); $resultArray = []; foreach ($categories as $key => $category) { ksort($category); foreach ($category as $cat) { natcasesort($cat); foreach ($cat as $k => $v) { $resultArray[$key][] = $v; } } } echo json_encode($resultArray);