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

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);

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?

Group rows on one column and form nested subarray with other column

Here is the thing I trying deal with
I have array which looks like this and have duplicates
$products = [
[
"product_name" => "Adidas1",
"address" => "street 2"
],
[
"product_name" => "Adidas2",
"address" => "street 2"
],
[
"product_name" => "Adidas3",
"address" => "street 2"
],
[
"product_name" => "Adidas4",
"address" => "street 2"
],
[
"product_name" => "Nike1",
"address" => "street name1"
],
[
"product_name" => "Nike2",
"address" => "street name1"
]];
Result that I need to get is below .
I did try different ways to do it but still can bring it to the finel result that have to come up
$final_result = [
[
"address" => "street 2",
"products" => [
"addidas1",
"addidas2",
"addidas3",
"addidas4",
]
],
[
"address" => "street name1",
"products" => [
"Nike1",
"Nike2",
]
]
any suggestion how to do it ?
here is my best solution that I tried
$stor_sorted = array();
foreach ($products as $product) {
if (array_count_values($product) > 1) {
$stor_sorted[] = ["address" => $product['address'], "items" => [$product['product_name']]];
}
}
try this code
$products = [
[
"product_name" => "Adidas1",
"address" => "street 2"
],
[
"product_name" => "Adidas2",
"address" => "street 2"
],
[
"product_name" => "Adidas3",
"address" => "street 2"
],
[
"product_name" => "Adidas4",
"address" => "street 2"
],
[
"product_name" => "Nike1",
"address" => "street name1"
],
[
"product_name" => "Nike2",
"address" => "street name1"
]];
$final_result = [];
foreach ($products as $pr){
$original_key = array_search($pr['address'], array_column($final_result, 'address'), true);
if($original_key === false){
$temp_array['address'] = $pr['address'];
$temp_array['products'] = [$pr['product_name']];
$final_result[] =$temp_array;
}else{
$final_result[$original_key]['products'][] = $pr['product_name'];
}
}
your result will be in final_result array
Use address values as temporary keys in your result array.
When an address is encountered for the first time, cast the product name as an array within the row and store the row.
On subsequent encounters, merely push the product name into the group's subarray.
When finished, re-index the result with array_values().
Code: (Demo)
$result = [];
foreach ($products as $row) {
if (!isset($result[$row['address']])) {
$row['product_name'] = (array)$row['product_name'];
$result[$row['address']] = $row;
} else {
$result[$row['address']]['product_name'][] = $row['product_name'];
}
}
var_export(array_values($result));
Same output with a body-less foreach() using array destructuring: (Demo)
$result = [];
foreach (
$products
as
[
'address' => $key,
'address' => $result[$key]['address'],
'product_name' => $result[$key]['product_name'][]
]
);
var_export(array_values($result));
Same output with functional style programming and no new globally-scoped variables: (Demo)
var_export(
array_values(
array_reduce(
$products,
function($result, $row) {
$result[$row['address']]['product_name'] = $row['product_name'];
$result[$row['address']]['address'][] = $row['address'];
return $result;
}
)
)
);

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

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.'
}';

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
)
)

Put nested array into one array

Suppose i have a array like this :
Array(
'1' => Array(
"ID" => 1,
"Name" => "name 1"
),
'2' => Array (
Array(
"ID" => 2,
"Name" => "name 2"
)
),
'3' => Array(
Array(
Array(
Array(
"ID" => 3,
"Name" => "name3"
)
)
),
'4' => Array (
Array {
"ID" => 4,
"Name" => "name 4"
),
Array(
"ID" => 5,
"Name" => "name 5"
),
Array(
"ID" => 6,
"Name" => "name 6"
)
);
number of sub-arrays is not ordered it may be 3, 4 or 5 etc...
and i wanted to get :
Array(
Array( "ID" => 1, "Name" => "name 1"),
Array( "ID" => 2, "Name" => "name 2"),
Array( "ID" => 3, "Name" => "name 3"),
Array( "ID" => 4, "Name" => "name 4"),
Array( "ID" => 5, "Name" => "name 5"),
Array( "ID" => 6, "Name" => "name 6"));
Is there an easy way to do this ?
EDIT :
Edited the above array to add :
'4' => Array (
Array {
"ID" => 4,
"Name" => "name 4"
),
Array(
"ID" => 5,
"Name" => "name 5"
),
Array(
"ID" => 6,
"Name" => "name 6"
)
);
which aren't nested but i still want them to be in my final array.
Thanks.
//Assuming your data is in $in
$out=array();
foreach($in as $k=>$v) {
while ((is_array($v)) && (isset($v[0]))) $v=$v[0];
//See below for next line
$out[]=$v;
}
print_r($out);
With the marked line being either $out[$k]=$v; or $out[]=$v; depending on wether you want to keep the 1st-level keys. In your desired output you do not ,so use the shown version
Edit
With you changed input array, you need to do something like
function addtoarray($inarray, &$outarray) {
foreach ($inarray as $i) {
if (!is_array($i)) continue;
if (isset($i['ID'])) $outarray[]=$i;
else addtoarray($i,$outarray);
}
}
$out=array();
addtoarray($in,$out);
print_r($out);
This was tested against your new input data
You could recurse through the array and check for the ID field.
function combine_array(array $src, array &$dest)
{
if( isset( $src['ID'] ) ) {
$dest[] = $src;
return;
}
foreach( $sub in $src ) {
combine_array( $sub, $dest );
}
}
Just wrote this off the top of my head, no testing, so it might have a few problems. But that's the basic idea.
This may work for you, assuming $array is the variable and php 5.3
//process
$array = array_map(function($block) {
$return = '';
foreach ($block as $sub) {
if (true === isset($sub['ID']) {
$return = $block;
break;
}
}
return $block;
}, $array);
array_filter($array); //remove empty elements
Wrote up a quick recursive function. You'll need to write any appropriate error handling and check the logic, since a discrepancy in your data could easily turn this into an infinite loop:
$output = array();
foreach ( $data as $d ) {
$output[] = loop_data( $d );
}
function loop_data( $data ) {
// Check if this is the right array
if( ! array_key_exists( "ID", $data ) ) {
// Go deeper
$data = loop_data( $data[0] );
}
return $data;
}

Categories