ignezio's avatar

How to Convert a Associative Array to A 2 dimensional array

I have the given array

    array:7 [▼
  "data" => "data"
  "id_1553539135251" => "<p>nsmn</p>"
  "about" => "about"
  "id_1553539141598" => "<p>uiu</p>"

i need to convert this associative array into a 2 dimentional array like the exsample below

array:3 [▼
  "id_1553539135251" => array:1 [▼
    "content" => "<p>nsmn</p>"
    "header" => "data"
]
  "id_1553539141598" => array:1 [▼
    "content" => "<p>uiu</p>"
    "header" => "about"
  ]
]

My current code seems to be missing some logic but i can quite figure out the desired result.

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

my current code returns an array but not in the correct format my overall question is how would i go about converting the associative array in example one to the layout of example two with dynamic data

0 likes
4 replies
jlrdw's avatar

Start with the keys, example $quy is your array

$keys = array_keys($quy);
for ($i = 0; $i < count($quy); $i++) {
          foreach ($quy[$i] as $key => $value) {
          // here work out what you need to do

Can take some trial and error.

Snapey's avatar

it would help if your data was structured better. Is there no way the form can be fixed? (assuming it comes as a form request data)

The way it is, the only structure you have is odd and even rows which is not a good recipe for reliability

bobbybouwmann's avatar

This bit of code does exactly that!

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

$result = [];

for ($i = 0; $i < count($array) / 2; $i++) {
    $subArray = array_slice($array, $i * 2, 2);
    
    $result[array_keys($subArray)[1]] = [
        'content' => array_values($subArray)[1],
        'header' => array_values($subArray)[0],
    ];
}

var_dump($result);

Note: It only works if they array is always build up like this. But it should give you a good overview of how something like this can be done

Let me know if you need any more help

Please or to participate in this conversation.