Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP multidimensional array convert to forms

Sorry for asking this idiot question, my head was blackout because of magento.

Here is the problem:

I have here an array:

array(2) {
  [0]=>
  array(3) {
    ["product_name"]=>
    string(12) "Test Product"
    ["product_qty"]=>
    string(6) "2.0000"
    ["product_price"]=>
    string(7) "15.0000"
  }
  [1]=>
  array(3) {
    ["product_name"]=>
    string(6) "Test 2"
    ["product_qty"]=>
    string(6) "3.0000"
    ["product_price"]=>
    string(7) "25.0000"
  }
}

How can I make transform this to:

<input type="hidden" name="product1" value="Test Product" />
<input type="hidden" name="amount1" value="2" />
<input type="hidden" name="qty1" value="15" />
<input type="hidden" name="product2" value="Test 2" />
<input type="hidden" name="amount2" value="3" />
<input type="hidden" name="qty2" value="25" />

Thanks for your answer.

like image 727
Jorge Avatar asked May 06 '11 18:05

Jorge


People also ask

How to convert Multidimensional array to object In PHP?

PHP Array: Associative, Multidimensional$get_object = json_decode(json_encode($array)); First, the json_encode($array) converts the entire multi-dimensional array to a JSON string. Then the json_decode($string) will convert the JSON string to a stdClass object.

How to convert Multidimensional array to JSON In PHP?

To convert PHP array to JSON, use the json_encode() function. The json_encode() is a built-in PHP function that converts an array to json. The json_encode() function converts PHP-supported data type into JSON formatted string to be returned due to JSON encode operation.

How we can convert a multidimensional array to string without any loop?

Maybe in case you need to convert a multidimensional array into a string, you may want to use the print_r() function. This is also called “array with keys”. By adding “true” as its second parameter, all the contents of the array will be cast into the string.


2 Answers

Try this:

foreach($array as $pKey=>$product){
   foreach($product as $key=>$option){
       echo "<input type='hidden' name='{$key}_{$pKey}' value='$option'/>\n";
   }
}

It will give you a result like this:

<input type='hidden' name='product_name_0' value='Test Product'/>
<input type='hidden' name='product_qty_0' value='2.0000'/>
<input type='hidden' name='product_price_0' value='15.0000'/>
<input type='hidden' name='product_name_1' value='Test 2'/>
<input type='hidden' name='product_qty_1' value='3.0000'/>
<input type='hidden' name='product_price_1' value='25.0000'/>

Here is a demo: http://codepad.org/Eg2mejZH

like image 144
Naftali Avatar answered Sep 29 '22 19:09

Naftali


foreach ($array as $i => $product) {
    foreach ($product as $key => $value) {
           $name = $key . $i;
           echo "<input type='hidden' name='$name' value='$value' />";
    }
}
like image 24
Tesserex Avatar answered Sep 29 '22 18:09

Tesserex