php - How to insert a foreach loop inside a multidimensional array - php

How to insert a foreach loop inside a multidimensional array ?
I have a multidimensional array that I use to connect my website to Mailchimp. I have to check with a foreach loop the number of products that the user buys, and add these insiede a array call "lines".
This is at moment my json code, that after I will send to Mailchimp:
$json_data = '{
"id": "2'. $order->id .'",
"customer": {
"id": "71",
"email_address": "'.$order->email.'",
"opt_in_status": true,
"company": "'.$order->company_name.'",
"first_name": "'.$order->pad_firstname.'",
"last_name": "'.$order->pad_lastname.'",
"orders_count": 1,
"total_spent": 86
},
"checkout_url": "https://www.mywebsite.it/en/checkout/confirmation/",
"currency_code": "EUR",
"order_total": 86,
"lines"[{
'.$line_result.'
}]
}';
The $line_result is where I try to add the array of the products.
I know is wrong.
all the array inside the "lines" need be like this:
"lines":[
{
data product 1 ...
},
{
data product 2 ...
}
]
This is my foreach:
foreach ($order->pad_products as $product) {
$line_result['line'] = array(
"id" => "$order->id",
"product_id" => "$product->pad_product_id",
"product_title" => "$product->title",
"product_variant_id" => "$product->id",
"product_variant_title" => "$product->title",
"quantity" => "$product->pad_quantity",
"price" => "$product->prezzo",
);
};
what is the correct way to insert this data and create a multidimensional array like the one I need?
Thank you.

You just need to store all $line_result in global variable, and then, bind it to your json model :
$results = [];
foreach ($order->pad_products as $product) {
$results[] = array(
"id" => $order->id,
"product_id" => $product->pad_product_id,
"product_title" => $product->title,
"product_variant_id" => $product->id,
"product_variant_title" => $product->title,
"quantity" => $product->pad_quantity,
"price" => $product->prezzo,
);
};
$data = json_decode($json_data, true);
$data['lines'] = $results;
$json = json_encode($data);
EDIT : Script array to json
$lines = [];
foreach ($order->pad_products as $product) {
$lines[] = array(
"id" => $order->id,
"product_id" => $product->pad_product_id,
"product_title" => $product->title,
"product_variant_id" => $product->id,
"product_variant_title" => $product->title,
"quantity" => $product->pad_quantity,
"price" => $product->prezzo,
);
}
$data = [
'id' => '2'.$order->id,
'customer' => [
'id' => '71',
'email_address' => $order->email,
'opt_in_status' => true,
'company' => $order->company_name,
'first_name' => $order->pad_firstname,
'last_name' => $order->pad_lastname,
'orders_count' => 1,
'total_spent' => 86
],
'checkout_url' => 'https://www.mywebsite.it/en/checkout/confirmation',
'currency_code' => 'EUR',
'order_total' => 86,
'lines' => $lines
];
$jsonData = json_encode($data, JSON_UNESCAPED_UNICODE);

I want say thank you to #adrianRosi for the help and the input he gives me.
In the end I find my solution, that it's json_encode the array before add into $data in json format.
in this way:
$product_list = [];
foreach ($order->pad_products as $product) {
$product_list[] = array(
"id" => "$id",
"..." => "...",
);
};
$data_products['lines'] = $product_list;
$json_products = json_encode($data_products);
$json_products_edit = substr($json_products, 1, -1); // to delete the {}
$prezzo_totale = $order->pad_price_total;
$json_data = '{
...
...
'.$json_products_edit.'
}';

Related

convert array to group keys and group values in PHP

Hello I have an array and want to group keys and values as shown below:
[
"agre" => "0"
"extr" => "0"
"inte" => "100"
]
I want to convert it to
{"labels":["agre","extr","inte"],"points":[0,0,100]}
Just create a new array of the keys and the values.
$data = [
"agre" => "0",
"extr" => "0",
"inte" => "100",
];
echo json_encode([
'labels' => array_keys($data),
'points' => array_map('intval', array_values($data))
]);
prints
{"labels":["agre","extr","inte"],"points":[0,0,100]}
Try this code.
<?php
$data = array(
"agre" => "0",
"extr" => "0",
"inte" => "100"
);
$newData = array('labels' => array(), 'points' => array());
foreach($data as $key => $value) {
$newData['labels'][] = $key;
$newData['points'][] = $value;
}
print_r($newData);
?>
Isn't this what you wanted?

Update array with post values

im currently trying to update an array with values from another one.
Basically there is a form where you can update data for an object, the form sends a json array like so:
{
"name": "Test2",
"address": "Adresas 2",
"object_id": "44",
"job_id": [
"31",
"33"
],
"amount": [
"500",
"500"
]
}
My goal is to update another array that is being fetched from the database with values of job_idd and amount.
The array from database looks like so:
{
"jobs": [
{
"id": "31",
"amount": "500",
"have": 250
},
{
"id": "33",
"amount": "500",
"have": 0
}
]
}
I need to update the second array values "amount" with the posted values from the first array "amount", but so that the second array still has the original "have" values
I tried using nested foreach method:
$object_id = $_POST['object_id'];
$data = json_encode($_POST);
$json = json_decode($data, true);
$i = 0;
foreach($json['job_id'] as $item) {
$job_id = $item;
$query33 = "SELECT * FROM `objektai` WHERE id='$object_id'";
$result33 = mysqli_query($conn, $query33) or die(mysqli_error($conn));
while($row2 = mysqli_fetch_array($result33)){
$job_info = $row2['info'];
}
$json_22 = json_decode($job_info, true);
foreach ($json_22['jobs'] as $key2 => $entry2) {
$have = $json_22['jobs'][$key2]['have'];
}
$result["jobs"][] = array(
'id' => $job_id,
'kiekis' => $json['amount'][$i],
'turima' => $have,
);
$i++;
}
Usinng the example above the foreach prints the values 2 times and my updated json "have"
has a value of 0, the "amount" entries are updated correctly
Thanks in advance for you help!
UPDATE
adding var_export($_POST):
array ( 'name' => 'Test2',
'address' => 'Adresas 2',
'object_id' => '44',
'job_idd' => array (
0 => '31',
1 => '33',
),
'darbo_kiekis' => array (
0 => '500',
1 => '500',
),
)
When you're looping through the array from the database, you need to compare the id value with $obj_id.
I've also shown below how to use a prepared statement to prevent SQL injection.
I've removed lots of unnecessary code:
No need to convert $_POST to/from JSON.
Use $i => in the foreach loop to get the array index.
You don't need a while loop when processing the query results if it only returns one row.
You don't need $key2, you can just use $entry2.
$object_id = $_POST['object_id'];
$query33 = "SELECT * FROM `objektai` WHERE id = ?";
$stmt33 = $conn->prepare($query33);
$stmt33->bind_param('i', $job_id);
foreach($_POST['job_id'] as $i => $job_id) {
$stmt33->execute();
$result33 = $stmt33->get_result();
$row2 = $result33->fetch_assoc();
$job_info = $row2['info'];
$json_22 = json_decode($job_info, true);
foreach ($json_22['jobs'] as $entry2) {
if ($entry2['id'] == $job_id) {
$result["jobs"][] = array(
'id' => $job_id,
'kiekis' => $json['amount'][$i],
'turima' => $entry2['have']
);
}
}
}

PHP sum up value in foreach separate

Hi I am new to php and I faced some problem when I need sum up array in foreach.
I had array like this:
$arrays = [
[
'orderid' => "1",
'price' => "100"
'rate' => "1"
],
[
'orderid' => "2",
'price' => "200"
'rate' => "5"
],
];
What I face when I using foreach, the price * rate will sum continuously but not sum up separately.
$bonus = array();
foreach($arrays as $data){
$bonus = $data['originalPrice'] * $data['rate'];
}
I also tried using array_map() but also cannot get my answer;
WHat I need about :
$array = [
[
'total' => 100;
],
[
'total' => 1000;
]
]
Any idea for help?
UPDATED: ALL THE ANSWER ARE CORRECTED, is the api data give me wrong info lol.
foreach($arrays as $data){
$bonus[]['total'] = $data['price'] * $data['rate'];
}
print_r($bonus);
You are using price so use that property and you need to push the value in the result array. Thus, you need to do:
<?php
$arrays=array(
array(
'orderid' => "1",
'price' => "100",
'rate' => "1"
),
array(
'orderid' => "2",
'price' => "200",
'rate' => "5"
)
);
$bonus = array();
foreach($arrays as $data){
array_push($bonus,$data['price'] * $data['rate']);
}
print_r($bonus);
?>
You can test this code at http://www.writephponline.com/
Foreach is fine, but you need to add to the bonus array rather than override with the result:
$bonus = array();
foreach($arrays as $data){
$bonus[] = array('total' => $data['originalPrice'] * $data['rate']);
}
This is adding arrays to the bonus array.

Remove from multidimensional array if has seen id before in an basic array

I would like in php to stop duplicate messages by logging msgid to a text file using something like this file_put_contents("a.txt", implode(PHP_EOL, $array1), FILE_APPEND);
and then converting it back to an array using $array1 = file("a.txt"); I would also like to delete messages from the array if they are from a set name
I know how to convert json to an array $array1 = json_decode($json, true);
Json Reply from an api that I cannot control
{
"API": "Online",
"MSG": [
{
"info": {
"name": "example"
},
"msg": "example",
"msgid": "example"
},
{
"info": {
"name": "example"
},
"msg": "example",
"msgid": "example"
}
]
}
Hi use the following code, first test it out accordingly
$uniqueMessages = unique_multidim_array($messages,'msg');
Usage : Pass the key as the 2nd parameter for which you need to check the uniqueness of array.
<?php
/* Function to handle unique assocative array */
function unique_multidim_array($array, $key) {
/* temp array to hold unique array */
$temp_array = array();
/* array to hold */
$i = 0;
/* array to hold the key for unique array */
$key_array = array();
foreach($array as $val) {
if (!in_array($val[$key], $key_array)) {
$key_array[$i] = $val[$key];
$temp_array[$i] = $val;
}
$i++;
}
return $temp_array;
}
$messages = array(
0 => array(
'info' => array(
'name' => 'example'
),
'msg' => 'example',
'msgid' => 'example'
),
1 => array(
'info' => array(
'name' => 'example 1'
),
'msg' => 'example 1',
'msgid' => 'example 1'
),
3 => array(
'info' => array(
'name' => 'example'
),
'msg' => 'example',
'msgid' => 'example'
)
);
echo '<pre>';
echo '*****************BEFORE***********************<br/>';
var_dump($messages);
echo '*****************AFTER***********************<br/>';
$uniqueMessages = unique_multidim_array($messages,'msg');
var_dump($uniqueMessages);
This works for me this is an modded function click here for original function
function RemoveElementByArray($array, $key, $seen){
foreach($array as $subKey => $subArray){
if(in_array($subArray[$key], $seen)){
unset($array[$subKey]);
}
}
return $array;
}
Example:
$array = array(
array("id" => "1", "name" => "example1"),
array("id" => "2", "name" => "example2"),
array("id" => "3", "name" => "example3"));
$SeenArray = array("1", "2");
print_r(RemoveElementByArray($array, "id", $SeenArray));
Result:
Array
(
[2] => Array
(
[id] => 3
[name] => example3
)
)

PHP - Push data to array in foreach loop [duplicate]

This question already has answers here:
PHP Append an array to a sub array
(2 answers)
Closed 2 years ago.
I want to achieve below array format:
{
"success": true,
"results": [
{
"name" : "Choice 1",
"value" : "value1",
"text" : "Choice 1"
},
{
"name" : "Choice 2",
"value" : "value2",
"text" : "Choice 2"
}
]
}
However, I am using PHP and a foreach loop, to return some values from my database:
//Search for clients in our database.
$stmt = $dbh->prepare("SELECT * FROM customers");
$stmt->execute();
$showAll = $stmt->fetchAll();
I then have my first part of the array, and my foreach loop:
$data = array(
"success" => false,
"results" => array()
);
foreach ($showAll as $client) {
$data_array[] =
array(
'name' => $client['name'],
'value' => $client['name'],
'text' => $client['name']
);
}
Above only outputs:
[
{
"name":"Choice 1",
"value":"value 1",
"text":"Choice 1"
},
{
"name":"Choice 2",
"value":"value2",
"text":"Choice 2"
}
]
So it is missing the top part of my original array - but I want to loop through each database results in "results": [ ... ]
Try this
$data = array(
"success" => false,
"results" => array()
);
foreach ($showAll as $client) {
$data['results'][] = array(
'name' => $client['name'],
'value' => $client['name'],
'text' => $client['name']
);
}
$data['success'] = true; // if you want to update `status` as well
echo json_encode($data);
After creating $data_array array just add few lines which i have in my post.
Try this code snippet here(with sample input)
ini_set('display_errors', 1);
foreach ($showAll as $client)
{
$data_array[] = array(
'name' => $client['name'],
'value' => $client['name'],
'text' => $client['name']
);
}
// add these lines to your code.
$result=array();
$result["success"]=true;
$result["results"]=$data_array;
echo json_encode($result);
try this as you have an array inside the $data_array on Key "Results" so you should use "results" as a key also and then try to push data in that array
foreach ($showAll as $client) {
$data_array["results"][] =
array(
'name' => $client['name'],
'value' => $client['name'],
'text' => $client['name']
);
}
You can simply use json_encode and push it to your result array
$data = array(
"success" => false,
"results" => array()
);
$result = [
[
"name" => "Choice 1",
"value" => "value 1",
"text" => "Choice 1"
],
[
"name" => "Choice 2",
"value" => "value2",
"text" => "Choice 2"
]
];
$data['results'] = json_encode($result);

Categories