How to loop through array of multiple arrays in php

Multi tool use
Multi tool use
The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


How to loop through array of multiple arrays in php



I am trying to loop through array of arrays in php. Usually get stalked with complex array sometimes but I need your kind assistance with this.



var_dump($array) produced the array below:


var_dump($array)


$arrayVal = array(6) {
["item_id"]=>
array(2) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
}
["request_explanation"]=>
array(2) {
[0]=>
string(7) "Welcome"
[1]=>
string(11) "Hello World"
}
["quantity"]=>
array(2) {
[0]=>
string(1) "4"
[1]=>
string(1) "4"
}
["unit_cost"]=>
array(2) {
[0]=>
string(1) "4"
[1]=>
string(1) "3"
}
["total_cost"]=>
array(2) {
[0]=>
string(1) "0"
[1]=>
string(1) "0"
}
["supporting_document"]=>
string(0) ""
}



My database table:



enter image description here



I want to be able to save each of the value in that array into the table above. Thanks for helping me.




2 Answers
2



Use the indexes of one of the sub-arrays to access all the other sub-arrays:


foreach ($array['item_id'] as $i => $item_id) {
$request_explanation = $array['request_explanation'][$i];
$quantity = $array['quantity'][$i];
// repeat this for all the columns
// Now you can insert all these variables into the database
}



Use a loop to build 2 separate arrays:


foreach($array['ExpensesList'] as $index => $val){
$array1[$index] = $array['ExpensesList'][$index][0];
$array2[$index] = $array['ExpensesList'][$index][1];
}



Then insert each array into your database individually.



This will not work if any sub array contains an index at 2, so this is explicitly for the example structure you provided.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

6dO Rdaf8qLoui,H gc Z2,b,zc 0Qn cIHRLc g ke,p2lC io JJrPZr4Nb
zvpB5MutwzPqp4z2rjaC5RHHHxU0tlzwh,ZS9iARV20hgt,gt8omtgg1vIf5

Popular posts from this blog

Keycloak server returning user_not_found error when user is already imported with LDAP

PHP parse/syntax errors; and how to solve them?

415 Unsupported Media Type while sending json file over REST Template