Home > Software design >  How to create multidimensional array from php post?
How to create multidimensional array from php post?

Time:11-11

how to create multidimensional & associative array from php post?

        $html .= '<td><input id="location" name="location['.$i.']" type="text"  placeholder="result data (kosongkan jika tidak diperlukan)" value=""/></td>';
        $html .= '<td><input id="msg" name="msg['.$i.']" type="text"  value="' . htmlspecialchars($key) . '"/></td>';
        $html .= '<td><input id="order_id" name="order_id['.$i.']" type="text"  value="' . htmlspecialchars($value) . '"/></td>';

i want to make array output like this:

[$_POST['location'] => [$_POST['msg']=>$_POST['order_id']]]

CodePudding user response:

You have made some simple errors

You can foreach over an array then you dont care how large or small it is. You also have a error in the variable used in $_POST.

Using the foreach( $arr as $index => $value) syntax gets you an index into the array you are processing, If all 3 arrays are always the same size you can then use that to reference the other arrays.

$arr = [];
foreach ( $_POST['location'] as $i => $locn ) {
    $arr[$locn][] = [ $_POST['msg'][$i] => $_POST['order_id'][$i] ];
}

It help to debug your code if you

Add error reporting to the top of your file(s) while testing right after your opening PHP tag for example. Even if you are developing on a server configured as LIVE you will now see any errors. <?php error_reporting(E_ALL); ini_set('display_errors', 1);

  • Related