Reputation: 313
I have an array of arrays that I loop through in my view to display them in a table and I have a confirmation button that I need on-click to store these table data in db. My question is how can I pass this array of arrays from the view to my controller so as to proceed with storing to db?
I have tried using a form and pass it as post data using json_encode() to convert array to string, but no luck. I get an error
Message: json_decode() expects parameter 1 to be string, array given
Can I somehow pass the array variable to the on-click function of my input field?
Thanks.
Upvotes: 1
Views: 2639
Reputation: 313
I found the solution to my problem. Here is what worked for me. I was passing my array of arrays as a string value in a hidden input field using
json_encode($array)
but the problem was that my keys was double quoted and as a result the
value="<?php echo json_encode($array);?>"
was breaking down...
The solution was to escape the characters, so I had to replace the above line with
value="<?php echo htmlspecialchars(json_encode($array));?>"
And in the controller I had to get my array from json with the following lines
$dataJson = $this->input->post('array');
$dataArray = json_decode(htmlspecialchars_decode($dataJson), true);
Thanks everyone for the answers!
Upvotes: 1
Reputation: 441
You can pass array in the url string like this:
?arr[]=val1&arr[]=val2 //pass as the url param
//in controller
var_dump($_GET["arr"]);
//result should be
array(2) { [0]=> string(4) "val1" [1]=> string(4) "val2" }
Upvotes: 1