Echo comma separated values in PHP - php

I have a invoice table in which three columns have comma-separated values. Now I want to show a report in details for each invoice.
For example,
Invoice_id=10
product=1,5,55
category=2,44,25
QTY= 55,2,10
So for the above invoice I want to show each product name and category with qty.

If they are in the right order and have a consistent correlation, you can do that.
For example, you can explode by ',' the fields and create the output in a for loop like this:
//you have to retrieve the data from database, the fields are strings
$product= "1,5,55"
$category= "2,44,25"
$QTY= "55,2,10"
//for each invoice:
$products = explode(',',$product);
$categories = explode(',',$category);
$QTYs = explode(',',$QTY);
for ($i = 0; $i < count($products); $i++){
echo "Product: " . $products[$i] . ", Category: " . $categories[$i] . ", Quantity: " . $QTYs[$i] . ".<br>";
}
hope it helps

foreach(explode(' ', 'Invoice_id=10 product=1,5,55 category=2,44,25 QTY=55,2,10') as $key => $value)
{
$temp[] = explode('=', $value);
}
foreach($temp as $key => $value)
{
$final[$value[0]] = explode(',', $value[1]);
}
echo '<pre>';
print_r($final);
output:
Array
(
[Invoice_id] => Array
(
[0] => 10
)
[product] => Array
(
[0] => 1
[1] => 5
[2] => 55
)
[category] => Array
(
[0] => 2
[1] => 44
[2] => 25
)
[QTY] => Array
(
[0] => 55
[1] => 2
[2] => 10
)
)

Related

PHP/CodeIgnitier Get a single value from this multimdimensionnal PHP array

I want to retrieve a single value from this php array.
My array in PHP is:
Array
(
[0] => stdClass Object
(
[id] => 27
[id_customer] => 19
[my_cart] => Array
(
[c81e728d9d4c2f636f067f89cc14862c] => Array
(
[id] => 2
[qty] => 1
[price] => 39000
[name] => HEBERGEMENT WEB MUTUALISE PREMIUM
[rowid] => c81e728d9d4c2f636f067f89cc14862c
[subtotal] => 39000
)
[a87ff679a2f3e71d9181a67b7542122c] => Array
(
[id] => 4
[qty] => 1
[price] => 150000
[name] => HEBERGEMENT WEB MUTUALISE ULTIMATE
[rowid] => a87ff679a2f3e71d9181a67b7542122c
[subtotal] => 150000
)
)
1
[created_at] => 2020-03-30
)
)
The problem is that I can not get qty, name, price
I tried by doing this in my foreach
foreach($cart_data as $cd){
echo 'ID Table: '.$cd->id.'<br>';
echo 'ID customer: '.$cd->id_customer.'<br>';
$data = $cd->my_cart;
if(is_array($data)){
foreach($data as $s){
echo 'My cart: '.$s;
}
}
}
But nothing is happened! I want to get price, name and qty.
In this line:
echo 'My cart: '.$s;
The variable $s holds an array, not a string. If you follow your data structure, the contents of $s would be similar to this:
Array (
[id] => 4
[qty] => 1
[price] => 150000
[name] => HEBERGEMENT WEB MUTUALISE ULTIMATE
[rowid] => a87ff679a2f3e71d9181a67b7542122c
[subtotal] => 150000
)
So, in order to get name, qty, price, you'd need to change your inner loop to something like this:
foreach ($data as $s) {
echo 'Product name: ' . $s['name'] . '<br>';
echo 'Quantity: ' . $s['qty'] . '<br>';
echo 'Price: ' . $s['price'] . '<br>';
}
What happens when you try to use an array as a string is that it shows up as the string "Array" and will trigger a PHP Notice: Array to string conversion in [location]. I'm guessing this error might be the reason you get nothing, instead of My cart: Array.
To get several keys from my_cart array, try to write the loop like this :
foreach($cart_data as $cd){
echo 'ID Table: '.$cd->id.'<br>';
echo 'ID customer: '.$cd->id_customer.'<br>';
$data = $cd->my_cart;
if(is_array($data)){
$filtered = [];
$keys = ['qty', 'name', 'price']; // the keys
$column_keys = array_flip($keys); // getting keys as values
foreach ($data as $key => $val) {
// getting only those key value pairs, which matches $column_keys
$item = array_intersect_key($val, $column_keys);
if (!empty($item))
$filtered[$key] = $item;
}
echo 'My cart: <br/>';
print_r($filtered);
}
}
I found the solution. When inserting into database I encode it like this htmlspecialchars(json_encode($data)) and decode in with json_decode while getting the $data. So now I have this:
foreach($cart_data as $cd){
echo 'ID Table: '.$cd->id.'<br>';
echo 'ID customer: '.$cd->id_customer.'<br>';
$data = json_decode($cd->my_cart);
foreach($data as $row){
echo $row->name;
echo $row->qty;
echo $row->price;
}
}

merge array values - PHP

I have two arrays:
First:
Array
(
[0] => Catalog No.:
[1] => H-B No.
)
Second array:
Array
(
[0] => Array
(
[0] => GG
[1] => 692
)
[1] => Array
(
[0] => VV
[1] => 693
)
)
I want o to merge them into one array to get this:
Array
(
[0] => Array
(
[0] => Catalog No.: GG
[1] => H-B No. 692
)
[1] => Array
(
[0] => Catalog No.: VV
[1] => H-B No. 693
)
)
I tried with array merge, but that works with keys and values, I want to merge only values from this two arrays into one, any help?
<?php
$first = ['Catalog No.:', 'H-B No.'];
$second = [['GG', 692],['VV', 693]];
$result = [];
foreach ($second as $key => $values) {
foreach ($values as $number => $value) {
if (!isset($first[$number])) {
continue;
}
$result[$key][] = $first[$number] . ' ' . $value;
}
}
var_dump($result);
Another way could be using array_map and prepend the values from $first to the current $arr
$result = array_map(function($arr) use ($first){
foreach($first as $key => $value) {
$arr[$key] = $value . ' ' . $arr[$key];
}
return $arr;
}, $second);
Php demo

PHP - array wrong output (need function help)

In the output of this function (at the end) you can see that the products are placed in every subArray. I want to pass through the function via an argument where the product needs to be added. The argument will be a variable on a different page: like if the variable has value "meal2" => product only needs to be added under array "meal2".
function addToMeal() {
$xmaaltijden = $_SESSION['xmaaltijden'];
$i=1;
while ( $i <= $xmaaltijden ) {
$schemas = array('maaltijd' . $i);
$i++;
$producten = $_SESSION['products'];
foreach ($schemas as $key => $schema){
foreach ($producten as $k => $product){
$variables[$schema][] = $product;
};
};
};
echo '<pre>' . print_r($variables,1) . '</pre>';
}
output:
Array
(
[meal1] => Array
(
[0] => 1
[1] => 3
[2] => 2
[3] => 9
)
[meal2] => Array
(
[0] => 1
[1] => 3
[2] => 2
[3] => 9
)
[meal3] => Array
(
[0] => 1
[1] => 3
[2] => 2
[3] => 9
)
)
Not:
foreach ($schemas as $key => $schema){
foreach ($producten as $k => $product){
$variables[$schema][] = $product;
};
But:
$yourVar = 'meal2';
foreach ($schemas as $key => $schema){
if ($schema === $yourVar) {
$variables[$schema] = $producten;
} else {
$variables[$schema] = array();
}
}

Organize or group data from multidimensional array

I have a multidimensional array that I'm having difficulty trying to group and sort for a particular need. Here is the array:
Array (
[0] => Array (
[0] => Joe Smith
[1] => Array (
[0] => 3
[1] => 9
)
)
[1] => Array (
[0] => John Doe
[1] => Array (
[0] => 6
[1] => 12
)
)
[2] => Array (
[0] => Jack Frost
[1] => Array (
[0] => 2
[1] => 4
)
)
)
What I want to do is sort the numbers from smallest to shortest (i.e. 2,3,4,6,9,12), but also keep the names associated with those numbers. For example:
2 (Jack Frost),
3 (Joe Smith),
4 (Jack Frost),
6 (John Doe),
9 (Joe Smith),
12 (John Doe)
Any ideas how to sort by number and keep the names together? Thanks
UPDATE 1
Here is the PHP code I've used to list the numbers in order:
$users = get_users();
$names = array();
$days = array();
foreach( $users as $user ) {
$names[] = $user->display_name;
$days[] = $user->member_day;
}
$result = array_map( null, $names, $days );
$mdays = array();
foreach( $days as $d ) {
foreach( $d as $d2) {
$mdays[] = $d2;
}
}
for( $i; $i<=31; $i++ ) {
if( in_array($i, $mdays) ) {
echo $i . '<br>';
}
}
In the above code, $result prints out the above Array. Also, the for loop sorts the "days".
The end goal is to have 31 blocks and fill in the block by number with the name.
You can do something like as
$result = [];
foreach ($arr as $key => $value) {
foreach ($value[1] as $v) {
$result[$v] = $value[0];
}
}
ksort($result);
print_r($result);
Output:
Array
(
[2] => Jack Frost
[3] => Joe Smith
[4] => Jack Frost
[6] => John Doe
[9] => Joe Smith
[12] => John Doe
)
Note: This'll work fine till none of the array array contains the same key
something like this should work, and at the end you can soert you array
$final_array=array();
foreach (array as $arr){
foreach($arr as $aaa){
$final_array[]=array($aaa,$arr[0])
}
}

Processing array and inserting in mysql table

Array
(
[pid] => Array
(
[0] => 2
[1] => 3
)
[price] => Array
(
[0] => 20
[1] => 20
)
[qty] => Array
(
[0] => 2
[1] => 1
)
)
i have an outcome of the above array from some processing. with this i need to update to database like below table
pid price qty
2 20 2
3 20 1
$i = 0;
while( $i < count( $YourArray['pid']) ) {
$query = "INSERT INTO `tableName`(`pid`, `price`, `qty`) VALUES( ?, ?, ? )";
$stmt = $con->prepare( $query );
$stmt->execute(
array(
$YourArray['pid'][$i],
$YourArray['price'][$i],
$YourArray['qty'][$i]
)
);
$i++;
}
Where, I used the pdo method of insertion.
for(i=0;i<amount;i++){
echo $array['pid'][i];
echo $array['price'][i];
echo $array['qty'][i];
}
Where amount must be a count of the amount of rows you have
Try this :
$array = array("pid" => array(2,3),"price" => array(20,20),"qty" => array(2,1));
array_unshift($array, null);
$res = call_user_func_array('array_map', $array);
echo "<pre>";
print_r($res);
Output :
Array
(
[0] => Array
(
[0] => 2
[1] => 20
[2] => 2
)
[1] => Array
(
[0] => 3
[1] => 20
[2] => 1
)
)
loop this array and add to DB - So that you can add two entries in DB
this is a wrong way of doing it, i would use an indexed array, and then build a foreach loop that will handle each 1 separately, something like:
$values = array();
$values[] = array(
'pid' => 2,
'price' => 20,
'qty' => 2
);
$values[] = array(
'pid' => 3,
'price' => 20,
'qty' => 1
);
and from this then build a foreach loop and run each query there
foreach ($values as $value) {
$query = "insert into blah
set pid = " . $value['pid'] . ",
price = " . $value['price'] . ",
qty = " . $value['qty'] . ";";
mysql_query($query);
}

Categories