How to add text to comma separated values in foreach loop? - php

I have data like in the image below, Im using foreach loop to show my data.
But I want to show my data like his, I want to add "IC" to all elements of Ids..
This is my current code..
<?php
foreach ($model as $mod) { ?>
<tr>
<td><?= $mod['discount']; ?></td>
<td><?= $mod['ids']; ?></td>
</tr>
<?php } ?>
What do i need to do to add "IC" to $mod['ids'] for each row to be IC10000, IC100000, IC10000, IC10000.

As i commented out to use- Explode the ID's by , then concatenate the IC and again putback
$model = array(array('discount' => '2000', 'ids' => '100,1000,1000,1000'), array('discount' => '2001', 'ids' => '100,1000,1000,1000'),array('discount' => '2002', 'ids' => '100,1000,1000,1000'));
foreach ($model as $k=> $mod) {
$mod_2 = preg_filter('/^/', 'IC', explode(',', $mod['ids']));
echo $mod['discount'].'-'.implode(', ', $mod_2).PHP_EOL;
}
Example: https://3v4l.org/5I3l0

Through foreach loop you can do it !
PHP
<?php
$ids = "100,200,300,400,500,600";
$ids_array = explode(",",$ids);
$new_ids = array();
foreach($ids_array as $values){
$new_ids[] = "IC".$values;
}
echo implode(",",$new_ids);
?>
OUTPUT
IC100,IC200,IC300,IC400,IC500,IC600

Related

Foreach loop inside loop : is it possible to sort the results?

On a WP website, I have a custom post type ("Clients") with 3 posts : John, Jack and Mary.
Inside each post, I have a "payments" repeater with 2 subfields ("date" and "amount").
I have a query that loops through all the posts(clients) and puts the payments in a table - 1 row per payment.
John - 12/01/2022 - 50€
John - 23/02/2022 - 170€
Jack - 02/12/2021 - 1000€
Jack - 07/03/2022 - 4000€
Mary - 10/02/2022 - 100€
Is there any way to order the rows of this table by date of payment ? So as I get to this result:
Jack – 02/12/2021 – 1000€
John – 12/01/2022 – 50€
Mary – 10/02/2022 – 100€
John – 23/02/2022 – 170€
Jack – 07/03/2022 – 4000€
I understand that I might have to do a complete different query, but I'm wondering if such a query is even possible, or if I have to put my payments in a separate custom post type (1 post per payment) in order to be able to sort them.
Here is my code:
<table>
<?php $args = array(
'post_type' => 'clients',
'posts_per_page' => '-1',
);
$post_query = new WP_Query($args);
if($post_query->have_posts() ) {
while($post_query->have_posts() ) {
$post_query->the_post();
$payments = get_field('payments');
if( $payments ) {
foreach( $payments as $payment ) {
$date = $payment['date'];
$amount = $payment['amount'];
?>
<tr>
<td><?php echo the_title(); ?></td>
<td><?php echo $date; ?></td>
<td><?php echo $amount; ?></td>
</tr>
<?php }}}} ?>
</table>
Changing the query is probably not the best strategy here. You can instead use a temporary array to store the data, then sort the array.
At the top of your script, define the array
$data = [];
Remove the HTML from the foreach, and instead populate the array
foreach ($payments as $payment) {
$date = $payment['date'];
$amount = $payment['amount'];
$data[] = [
'title' => get_the_title(),
'date' => $date,
'amount' => $amount
];
}
Once the loop is ended, sort the array with a custom usort function based on the date
usort($data, function($a, $b) {return strtotime($a['date']) - strtotime($b['date']);})
Finally use the array to loop and echo your table
<table>
<?php foreach($data as $d) { ?>
<tr>
<td><?php echo $d['title']; ?></td>
<td><?php echo $d['date']; ?></td>
<td><?php echo $d['amount']; ?></td>
</tr>
<?php } ?>
</table>
Complete Code
<?php
$data = [];
$args = array(
'post_type' => 'clients',
'posts_per_page' => '-1',
);
$post_query = new WP_Query($args);
if ($post_query->have_posts()) {
while ($post_query->have_posts()) {
$post_query->the_post();
$payments = get_field('payments');
if ($payments) {
foreach ($payments as $payment) {
$date = $payment['date'];
$amount = $payment['amount'];
$data[] = [
'title' => get_the_title(),
'date' => $date,
'amount' => $amount
];
}
}
}
}
usort($data, function($a, $b) {return strtotime($a['date']) - strtotime($b['date']);})
?>
<table>
<?php foreach($data as $d) { ?>
<tr>
<td><?php echo $d['title']; ?></td>
<td><?php echo $d['date']; ?></td>
<td><?php echo $d['amount']; ?></td>
</tr>
<?php } ?>
</table>

Count images from dirs and show less on top

I am using this code to display the total files in different directories, all good but for example cats=50 then dogs=30 and fish=10. how can I make something so that I get fish on top then dogs and finally cats..
function scan_dir($path){
$ite=new RecursiveDirectoryIterator($path);
$nbfiles=0;
foreach (new RecursiveIteratorIterator($ite) as $filename=>$cur) {
$nbfiles++;
}
if($nbfiles > 2) $nbfiles = $nbfiles - 2;
return $nbfiles;
}
$dogs = scan_dir('/home/dogs/');
$cats = scan_dir('/home/cats/');
$fish = scan_dir('/home/fish/');
<table border="1">
<tr><td><b>Animal</b></></></td><td><b>Total Files</b></></></td></tr>
<tr><td>Dogs</td><td><?=$dogs?></td></tr>
<tr><td>Cats</td><td><?=$cats?></td></tr>
<tr><td>Fish</td><td><?=$fish?></td></tr>
</table>
Quick and dirty:
$dogs = scan_dir('/home/dogs/');
$cats = scan_dir('/home/cats/');
$fish = scan_dir('/home/fish/');
$arr = array("Dogs" => $dogs, "Cats" => $cats, "Fish" => $fish);
asort($arr);
echo '<table border="1">';
echo "<tr><td><b>Animal</b></></></td><td><b>Total Files</b></></></td></tr>";
foreach ($arr as $key=>$value) {
echo "<tr><td>$key</td><td>$value</td></tr>";
}
echo "</table>";
With a working example.
$array = array($dogs => 'dogs', $cats => 'cats', $fish => 'fish');
ksort($array); //sorts array the way you want
This should work.
<?php
function scan_dir($path){
$count = 0;
$it = new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS);
foreach (new RecursiveIteratorIterator($it) as $dummy) {
++$count;
}
return $count;
}
$animals = array(
'Dogs' => '/home/dogs/',
'Cats' => '/home/cats/',
'Fish' => '/home/fish/',
);
foreach ($animals as $animal => $path) {
$animals[$animal] = scan_dir($path);
}
arsort($animals);
?>
<table border="1">
<tr><td><b>Animal</b></td><td><b>Total Files</b></td></tr>
<?php foreach ($animals as $animal => $count): ?>
<tr><td><?=$animal?></td><td><?=$count?></td></tr>
<?php endforeach; ?>
</table>

Getting values from foreach

i have code which was written by a previous developer in our organization which says:
< ?php
foreach($response as $key => $value) {
?>
<tr>
<td><?php echo $key; ?></td>
<td><?php echo $value; ?></td>
</tr>
<?php
}
?>
i am very new to php and i dont know how to get values of $key[1]...$key[20] & $value[1]...$value[20] from this above code, since the above code writes 20 lines of values
I dont know if i am able to express this code problem in front of you correctly or not. sorry for my bad english.
As I understand your question, you want to have numerical indices..?
$key = array_keys($response);
$value = array_values($response);
Then you can use
$key[1]...$key[20] & $value[1]...$value[20]
< ?php
$keysarray = array();
$valuesarray = array();
int i = 0;
foreach($response as $key => $value) {
?>
<tr>
<td><?php $keysarray[i]= $key; echo $key; ?></td>
<td><?php $valuesarray[i]= $value; echo $value; ?></td>
</tr>
<?php
i++;
}
?>
The whole idea with a foreach loop is so you don't need to access the various indexes inside the array.
in your example, $response is an array.
during each iteration, the key/index of the array is assigned to $key and the value is assigned to $value.
eg.
$response = array('hello', 'goodbye');
// which is essentially the same as:
$response = array(0 => 'hello', 1 => 'goodbye');
during the first iteration of the foreach loop:
// first item in the array has an index of 0 and value of 'hello'
$key == 0;
$value == 'hello';
during pass two:
$key == 1;
$value == 'goodbye';
If your array $response is array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); then,
<?php
$response= array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($response as $key => $value) {
?>
<tr>
<td><?php echo $key; ?></td>
<td><?php echo $value; ?></td>
</tr>
<?php
}
Will Out put,
Peter 35
Ben 37
Joe 43
If $response is array("35","37","43");
then It will Out put,
0 35
1 37
2 43
In first case, Key will be as you given. It is known as Associative Arrays. Second, keys will be default from 0. It is Numeric arrays. No big deal.

Organizing results by category Redux

I am trying to expand on my question asked here: Creating a multi-dimensional array from query
I have added a category description to my categories table but I cannot figure out how to add it to the code below and display each category description for each category.
Here is the code I am using to display the items by category:
$itemcategories = array();
while ($row = mysqli_fetch_array($result))
{
$head = $row['category'];
$itemcategories[$head][] = array(
'id' => $row['id'],
'title' => $row['title'],
'itemdesc' => $row['itemdesc'],
'price' => $row['price'],
'special' => $row['special']
);
}
<?php foreach ($itemcategories as $head => $items) { ?>
<h3><?php echo $head; ?></h3>
<table class="chart">
<?php foreach ($items as $item) { ?>
<tr><td><?php echo $item['itemdesc']; ?></td></tr>
<?php } ?>
</table>
<?php } ?>
// to initial variable holder
$categories = $items = array();
// looping mysql result
while ($row = mysqli_fetch_array($result))
{
// to get category name
$head = $row['category'];
// avoid excessive setting of $categories
if (!isset($categories[$head]))
{
$categories[$head] = $row['descrption'];
}
// assign mysql result to $items
$items[$head][] = $row;
}
// free mysql result
mysql_free_result($result);
// loop all $categories
foreach ($categories as $head=>$desc)
{
// this is my example for printing HTML
// you can use heredoc syntax
// or stick to your existing format
echo "<h3>{$head} - {$desc}</h3><table class="chart">";
foreach ($items[$head] as $item)
{
// print item description
echo "<tr><td>{$item['itemdesc']}</td></tr>";
}
echo "</table>";
}

Creating a multi-dimensional array from query

I am using the code below to create a multi-dimensional array from a query so that I can organize the results by category but it only gets me 2 columns (category, agency).
I am not sure how I can alter this so that I can get 4 columns (category, agency, description, website). Any help is greatly appreciated.
$categories = array();
while ($row = mysqli_fetch_array($result))
{
$category = $row['category'];
$categories[$category][] = $row['agency'];
}
<?php
foreach ($categories as $category => $agencies)
{
?>
<h3><?php echo $category; ?></h3>
<table class="chart">
<?php
foreach ($agencies as $agency)
{
?>
<tr><td><?php echo $agency; ?></td></tr>
<?php
}
?>
</table>
<?php
}
?>
You could store the individual row results as an associative array:
$categories[$category][] = array(
'agency' => $row['agency'],
'description' => $row['description'],
'website' => $row['website']
);

Categories