I am new to PHP and i'm having a multidimensonal array. S i dug around about how to loop through the said array. Fortunately i got around that, but cannot seem to get each individual value separately. Let me show you what i mean:
This is my array:
Array
(
[0] => Array
(
[city] => Nairobi
[email] => dummy@email.com
[land_mark] => dummylandmark
[order_at] => dummytime
[payment_mode] => dummymode
[phone] => dummyphone
[receipt_code] => dummycode
[shipping_mode] => dummymode
[user_name] => dummyuser
[products] => Array
(
[0] => Array
(
[amount] => 2000
[name] => dummyname
[p_id] =>
[quantity] => 1
[subtotal] => 1
)
[1] => Array
(
[amount] => 2500
[name] => dummyname1
[p_id] =>
[quantity] => 1
[subtotal] => 1
)
)
)
)
JSON Array:
[
{
"receipt_code": "2016-12-17_23:09:55_obpekqaqdn",
"payment_mode": "Cash On Delivery",
"city": "Nairobi",
"email": "admin@buyathome.com",
"phone": "0715611306",
"order_at": "2016-12-17 23:09:55",
"user_name": "Admin",
"shipping_mode": "I'll Collect Myself",
"land_mark": "Postal office"
},
{
"products": [
{
"amount": 9000,
"description": "Experience with the Itel phone ",
"id": 45,
"quantity": "1",
"title": "Itel"
},
{
"amount": 200,
"description": "Do BBS fee r be ft gr",
"id": 46,
"quantity": "1",
"title": "The he hd"
}
]
}
]
And the snippet:
// Multi-dementional Source Array
//convert json object to php associative array
$data = json_decode(preg_replace('/\s+/', '', $jsondata), true);
// Output array
displayArrayRecursively($data);
/**
* Recursive function to display members of array with indentation
*
* @param array $arr Array to process
* @param string $indent indentation string
*/
function displayArrayRecursively($arr, $indent='') {
if ($arr) {
foreach ($arr as $value) {
if (is_array($value)) {
//
displayArrayRecursively($value, $indent . '--');
} else {
// Output should be inserted into mysql database
//but this method outputs all values into a single string
echo "$value";
}
}
}
}
This outputs:
Nairobi
dummy@email.com
dummylandmark
dummytime
dummymode
dummyphone
dummycode
dummymode
dummyuser
2000
dummyname
1
1
2500
dummyname1
1
1
My code for insertion:
$sql_query="insert into purchases (user_name, city, p_id,p_name,sub_total,quantity,email,landmark,order_at,payment_mode,phone,receipt_code,shipping_mode ) values ('$user_name','$city','$p_id','$p_name','$sub_total','$quantity','$email','$landmark','$order_at','$payment_mode','$phone','$receipt_code','$shipping_mode');";
if(mysqli_query($conn,$sql_query)){
//echo "<h3> Data Insert success</h3>";
$response["success"]=true;
$response["message"]="Purchase created successfully";
echo json_encode($response);
}
else{
$response["success"]=false;
$response["error"]=mysqli_error($conn);
$response["message"]="Creating purchase failed, please retry";
echo json_encode($response);
}
As one string. But i wanted to add each individual value into mysql database. Any suggestions?
</div>
Solved it by using:
foreach($data['products'] as $key => $val)
{
$product_id = $val['p_id)'];
$product_name = $val['name'];
$product_subtotal = $val['amount'];
$product_quantity = $val['quantity'];
print_r ($product_name);
//insert into mysql table
$sql_query="insert into purchases (user_name, city, p_id,p_name,sub_total,quantity,email,landmark,order_at,payment_mode,phone,receipt_code,shipping_mode ) values ('$user_name','$city','$product_id','$product_name','$product_subtotal','$product_quantity','$email','$landmark','$order_at','$payment_mode','$phone','$receipt_code','$shipping_mode');";
if(mysqli_query($conn,$sql_query)){
//echo "<h3> Data Insert success</h3>";
$response["success"]=true;
$response["message"]="Purchase created successfully";
echo json_encode($response);
}
else{
$response["success"]=false;
$response["error"]=mysqli_error($conn);
$response["message"]="Creating purchase failed, please retry";
echo json_encode($response);
}
}
Will update function with sql injections
</div>
//Code by :: GM
//REPLACE $data with your data source and include your DB connection
$data = ['city' => 'Nairobi', 'email' => 'dummy@email.com', 'products' => [array('amount' => 2000, 'name' => 'dummy_product_name', 'p_id' => 1, 'quantity' => 1, 'subtotal' => 1), array('amount' => 2500, 'name' => 'second_dummy_product_name', 'p_id' => 2, 'quantity' => 7, 'subtotal' => 1)]];
$insert_query_int = 'INSERT INTO purchases SET ';
$insert_query = $insert_query_int;
$query_statement_array=[];
$part_1_store='';
foreach ($data as $key => $value) {
//checks if value is string or an array
if (!is_array($value)) {
//if value is string
$part_1 = "$key = '".$value."', ";
$part_1_store.=$part_1;
$insert_query.= $part_1;
} else {
//if value is an array
//FOR EACH PRODUCT
$product_index = 0;
foreach ($value as $key2 => $value2) {
foreach ($value2 as $key3 => $value3) {
//add product details to the query statement
$insert_query .= "$key3 = '" . $value3 . "', ";
}
//PRIMING THE LOOP
if($product_index!=0){
//add product details to the query statement
$insert_query = $insert_query_int.$insert_query;
}
//Remove last comma from query string
$insert_query = rtrim(trim($insert_query),',');
//Store query statement in an array
$query_statement_array[] =$insert_query;
$insert_query = $part_1_store;
$product_index++;
}
}
}
//INSERT DATA TO DB
if (!$conn->multi_query(implode($query_statement_array,';'))) {
//fail response
$response["success"]=false;
$response["error"]=mysqli_error($conn);
$response["message"]="Creating purchase failed, please retry";
echo json_encode($response);
die();
}
do {
if ($res = $conn->store_result()) {
$res->free();
}
} while ($conn->more_results() && $conn->next_result());
//success response
$response["success"]=true;
$response["message"]="Purchase created successfully";
echo json_encode($response);
// you should consider normalizing your tables