phparraysgroupingassociative-array

Group a flat associative array by elements with a certain key prefix and accumulate preceding elements into the parent group


I need to convert an associative array to a 2 dimensional array. The original array is as follows.

$data = [
    "data" => "data",
    "id_1553539135251" => "<p>nsmn</p>",
    "about" => "about",
    "id_1553539141598" => "<p>uiu</p>",
]

My code:

$data = $request->all();
$json = array();
foreach ($data as $key => $value) {
    if (strpos($key, 'id') !== false) {
        $json[$key]['content'] = $value;
    }
}

I need the following output.

[
    "id_1553539135251" => ["content" => "<p>nsmn</p>", "data" => "data"],
    "id_1553539141598" => ["content" => "<p>uiu</p>", "about" => "about"]
]

but my code outputs

[
    "id_1553539135251" => ["content" => "<p>nsmn</p>"],
    "id_1553539138029" => ["content" => "<p>jjkjk</p>"],
    "id_1553539141598" => ["content" => "<p>uiu</p>"],
]

Solution

  • $test = array(
        array(
            "data" => "data",
            "id_1553539135251" => "<p>nsmn</p>",
            "about" => "about",
            "id_1553539141598" => "<p>uiu</p>"
        ),
    );
    
    $output = array();
    foreach ($test as $item) {
        $i = 0;
        $tt = '';
        foreach ($item as $k => $v) {
            if (strpos($k, 'id') !== false) {
                $output[$k] = array(
                    'content' => $item[$k],
                    'header' => $tt,
                );
            } else {
                $tt = $v;   
            }
        }
    }
    print_r($output);