Foreach where first four characters are the same - php

I have a dir with files like:
0000_01.jpg
0000_02.jpg
0000_03.jpg
2000_01.jpg
2000_02.jpg
2800_01.jpg
3200_01.jpg
And I want to get a table showing me which numbers are available for each article (0000, 2000, 2800, 3200 and so on).
I got this:
$files = glob('new/' . $map . '*.{jpg}', GLOB_BRACE);
foreach($files as $file) {
}
Now I need to check if the four characters are matching and check is _01, _02 and _03 are available or not.
I know about the php function substr() but I just can't figure out how to get that implemented in the foreach or something..
I want to get a table showing me like this:
artnr _01 _02 _03
0000 x x x
2000 x x
2800 x
..
Can anyone point me in the right direction of doing this?

PHP code
$files = array(
"0000_01.jpg",
"0000_02.jpg",
"0000_03.jpg",
"2000_01.jpg",
"2000_02.jpg",
"2800_01.jpg",
"3200_01.jpg",
);
$arr = array();
foreach ($files as $file) {
$arr[substr($file, 0, 4)][substr($file,5, 2)] = true;
}
and you can check the existance of '01' in '0000' by :
if ($arr["0000"]["01"])
Result
var_export($arr) :
array (
'0000' =>
array (
'01' => true,
'02' => true,
'03' => true,
),
2000 =>
array (
'01' => true,
'02' => true,
),
2800 =>
array (
'01' => true,
),
3200 =>
array (
'01' => true,
),
)
Creating the table
<table>
<tr>
<td width="80">artnr</td>
<td width="80">_01</td>
<td width="80">_02</td>
<td width="80">_03</td>
</tr>
<?php foreach ($arr as $key => $value) { ?>
<tr>
<td><?php echo $key ?></td>
<td><?php echo $value['01'] ? "X" : "" ?></td>
<td><?php echo $value['02'] ? "X" : "" ?></td>
<td><?php echo $value['03'] ? "X" : "" ?></td>
</tr>
<?php } ?>
</table>
Result

If I understood your question correctly, then you might use array_column() and array_unique() to get column titles and row headers:
<?php
header('Content-Type: text/plain; charset=utf-8');
$files = [
"0000_01.jpg",
"0000_02.jpg",
"0000_03.jpg",
"2000_01.jpg",
"2000_02.jpg",
"2800_01.jpg",
"3200_01.jpg",
];
$buffer = array_map(
function($name){ return explode('_', $name); },
$files
);
$groups = array_unique(array_column($buffer, 0));
$columns = array_unique(array_column($buffer, 1));
print_r($groups);
print_r($columns);
?>
Shows:
Array
(
[0] => 0000
[3] => 2000
[5] => 2800
[6] => 3200
)
Array
(
[0] => 01.jpg
[1] => 02.jpg
[2] => 03.jpg
)
Then build their intersection:
foreach($groups as $group){
foreach($columns as $column){
if(in_array("{$group}_{$column}", $files)){
echo "{$group}_{$column}", ' <- exists', PHP_EOL;
} else {
echo "{$group}_{$column}", ' <- not exists', PHP_EOL;
}
}
}
Shows:
0000_01.jpg <- exists
0000_02.jpg <- exists
0000_03.jpg <- exists
2000_01.jpg <- exists
2000_02.jpg <- exists
2000_03.jpg <- not exists
2800_01.jpg <- exists
2800_02.jpg <- not exists
2800_03.jpg <- not exists
3200_01.jpg <- exists
3200_02.jpg <- not exists
3200_03.jpg <- not exists

Another solution:
$a=array(
'0000_01.jpg',
'0000_02.jpg',
'0000_03.jpg',
'2000_01.jpg',
'2000_02.jpg',
'2800_01.jpg',
'3200_01.jpg');
$result_array=array();
foreach ($a as $item) {
list($art, $artnr) = array_slice(str_split($item, 4),0,2);
$result_array[$art][] = substr($artnr,1,-1);
}
print '<pre>';
print_r($result_array);
print '</pre>';
Output:
Array
(
[0000] => Array
(
[0] => 01
[1] => 02
[2] => 03
)
[2000] => Array
(
[0] => 01
[1] => 02
)
[2800] => Array
(
[0] => 01
)
[3200] => Array
(
[0] => 01
)
)
Related question: Grouping and resorting values in PHP array using substrings

how about this:
<?php
$files = array('0000_01.jpg', '0000_02.jpg', '0000_03.jpg', '2000_01.jpg', '2000_02.jpg', '2800_01.jpg', '3200_01.jpg');
?>
<!DOCTYPE html>
<html>
<head>
<title>testing</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="jquery.js" type="text/javascript"></script>
</head>
<body>
<?php
$list = array();
foreach ($files as $file) {
preg_match('/(\d+).?(\d+)\./', $file, $match);
$name = $match[1];
$col = $match[2];
$list[$col][] = $name;
}
foreach ($list as $key => $item) {
foreach ($item as $value) {
echo "$key, $value<br/>";
}
}
?>
</body>
</html>

<?php
$files = glob('new/' . $map . '*.{jpg}', GLOB_BRACE);
$tableArr = array();
foreach($files as $file) {
$fileNameArr = explode('_', $file) {
if(count($fileNameArr) == 2 AND strlen($fileNameArr[0]) == 4 AND strlen($fileNameArr[1]) == 2) {
$tableArr[$fileNameArr[0]][$fileNameArr[1]] = 'x';
}
}
}
?>
<table>
<thead>
<tr>
<th>
artnr
</th>
<?php
foreach(array_keys($fileNameArr) as $key) {
?>
<th><?=$key?></th>
<?php
}
?>
</tr>
</thead>
<tbody>
<?php
foreach($fileNameArr as $key=>$row) {
?>
<tr>
<td><?=$key?></td>
<?php
foreach($row as $col) {
?>
<td><?=$col?></td>
<?php
}
?>
</tr>
<?php
}
?>
</tbody>
</table>

Why not a regular expression?
for($i=1;i<=3;i++){
$result = preg_match("/_0"+$i+"/",$file);
}
preg_match on PHP.net

Related

keys and values of dynamically generated array

i have an array:
Array
(
[0] => Array
(
[Dated] => 2017-04-01
[Nadeem] => 1995
[NadeemKaat] => 40
[Ali] => 0
[AliKaat] => 0
[Usman] => 0
[UsmanKaat] => 0
)
[1] => Array
(
[Dated] => 2017-04-06
[Nadeem] => 0
[NadeemKaat] => 0
[Ali] => 4800
[AliKaat] => 96
[Usman] => 0
[UsmanKaat] => 0
)
[2] => Array
(
[Dated] => 2017-04-20
[Nadeem] => 0
[NadeemKaat] => 0
[Ali] => 0
[AliKaat] => 0
[Usman] => 2100
[UsmanKaat] => 42
)
)
i want to print out this array values like this:
Date | Nadeem | Ali | Usman
2017-04-01 | 1995 | |
2017-04-06 | | 4800 |
2017-04-20 | | |2100
i am confuse here how to handle this kind of array, please help me out
i am trying with simply foreach loop
foreach ($stock as $key => $value)
{
echo $key . $value;
}
Try this:
if (!empty($stock)) {
echo '<table><tr>';
foreach ($stock[0] as $key => $value)
{
echo '<th>' . $key . '</th>';
}
echo '</tr>';
foreach ($stock as $value)
{
echo '<tr>';
foreach ($value as $key2 => $field) {
echo '<td>' . $field . '</td>';
}
echo '</tr>';
}
echo '</table>';
}
#Shafat Ahmad try this below one:
<?php
$stock = array(
array(
"Dated" => "2017-04-01",
"Nadeem" => 1995,
"NadeemKaat" => 40,
"Ali" => 0,
"AliKaat" => 0,
"Usman" => 0,
"UsmanKaat" => 0
),
array(
"Dated" => "2017-04-06",
"Nadeem" => 0,
"NadeemKaat" => 0,
"Ali" => 4800,
"AliKaat" => 96,
"Usman" => 0,
"UsmanKaat" => 0
),
array(
"Dated" => "2017-04-20",
"Nadeem" => 0,
"NadeemKaat" => 0,
"Ali" => 0,
"AliKaat" => 0,
"Usman" => 2100,
"UsmanKaat" => 42
)
);
?>
<table align="center" border="1">
<tr>
<th>Date</th>
<th>Nadeem</th>
<th>Ali</th>
<th>Usman</th>
</tr>
<?php
foreach ($stock as $value) {
?><tr>
<th><?php echo $value["Dated"] ?></th>
<th><?php echo $value["Nadeem"] ?></th>
<th><?php echo $value["Ali"] ?></th>
<th><?php echo $value["Usman"] ?></th>
</tr><?php
}
Try inner loops
// print header
foreach ($stock[0] as $key => $value) {
echo $key. ' | '
}
// print data
foreach ($stock as $item)
{
foreach ($item as $value) {
echo $value . ' | '
}
}
And then do a little bit play with changing | with <tr>, <td> and so on if you want proper table.
Or you can use
$header = array_keys($stock[0]);
echo '<table><tr><th>';
echo implode('</th><th>', $header);
echo '</th></tr>';
// print data
foreach ($stock as $item) {
echo '<tr><td>';
echo implode('</td><td>', $item);
echo '</td></tr>';
}
echo '</table>';
Try this:
foreach($stock as $data) {
echo $data['Dated'].' | '.($data['Nadeem'] ? $data['Nadeem'] : "") .' | '.$data['NadeemKaat'].' | '.$data['Ali'].' | '.$data['AliKaat'].' | '.$data['Usman'].' | '.$data['UsmanKaat'].'<br>';
}
Here is sample program. Maybe it'll help you.
// user data can be dynamic
$userData = array('Nadeem', 'Ali', 'Usman');
// tblRows data can also be dynamic
$tblRowsData = array(
'2017-04-01' => array('Nadeem'=>1995, 'Ali'=>'', 'Usman'=>''),
'2017-04-06' => array('Nadeem'=>'', 'Ali'=>4800, 'Usman'=>''),
'2017-04-20' => array('Nadeem'=>'', 'Ali'=>'', 'Usman'=>2100)
);
echo "<table border=1>";
echo "<tr>";
echo "<td>Date</td>";
foreach ($userData as $key => $value) {
echo "<td>$value</td>";
}
echo "</tr>";
foreach ($tblRowsData as $key => $value) {
echo "<tr>";
echo "<td>$key</td>";
foreach ($userData as $key1 => $value1) {
echo "<td>".$value[$value1]."</td>";
}
echo "</tr>";
}
echo "</table>";
$keys = array_keys($some[0]);
$theader = implode("\t", $keys);
echo $theader;
foreach ($some as $one) {
echo "\n";
for ($i = 0; $i < count($keys); $i++) {
echo $one[$keys[$i]] . "\t";
}
}
Assuming structure of your data doesn't change and $some is your given above array
Output :
Dated Nadeem NadeemKaat Ali AliKaat Usman UsmanKaat
2017-04-01 1995 40 0 0 0 0
2017-04-06 0 0 4800 96 0 0
2017-04-20 0 0 0 0 2100 42
A bit shit coded, fast written solution)))
$data = [];
foreach($input as $value) {
foreach($value as $person => $count) {
if($person !== 'Dated') {
$data[$value['Dated']][$person] = $count;
}
}
}
if(!$data) {
die('empty');
}
$persons = array_keys(reset($data));
$html = '<table border="1"><thead>
<th>Date</th>';
foreach($persons as $key) {
$html .= "<th>{$key}</th>";
}
$html .= '</thead><tbody>';
while($temp = array_splice( $data, 0, 1 )) {
$date = array_keys($temp)[0];
$html .= "<tr><td>".$date."</td>";
foreach($persons as $name) {
$val = isset($temp[$date][$name]) ? $temp[$date][$name] : '-';
$html .= "<td>".$val."</td>";
}
$html .= "</tr>";
}
$html .= '</tbody></table>';
die($html);
Where input like
$input = [
[
'Dated' => '2017-04-01',
'Nadeem' => 1995,
'NadeemKaat' => 40,
'Ali' => 0,
'AliKaat' => 0,
'Usman' => 0,
'UsmanKaat' => 0
],
[
'Dated' => '2017-05-11',
'Nadeem' => 123,
'NadeemKaat' => 40,
'Ali' => 3,
'AliKaat' => 0,
'Usman' => 0,
'UsmanKaat' => 0
]
];
Output in HTML:

How to find id in an array of categories

<?php
$categories = [
133 => 'Siomay',
123 => 'Indonesian',
20 => 'Bento',
];
$input_categories = [
'Siomay',
'Indonesian',
'Bento',
'Yoghurt',
];
How to get id categories? The example shown
Results:
133
123
20
-1 // Miss (-1)
To get the IDs in a loop:
foreach($categories as $key=>$value)
{
echo $key . "<br />";
}
That will output
133
123
20
I assume you should show -1 when there is no appropriate value? If it's all about, try this:
<?php
$categories = [
133 => 'Siomay',
123 => 'Indonesian',
20 => 'Bento',
];
$input_categories = [
'Siomay',
'Indonesian',
'Bento',
'Yoghurt',
];
foreach($input_categories as $input_category)
{
if(in_array($input_category, $categories))
echo array_search($input_category, $categories).'<br/>';
else
echo '-1<br/>';
}
Output:
133
123
20
-1
You can use array_keys() method for this. like below:
$ids = array_keys($categories);
echo "<pre>";
print_r($ids);
foreach ( $categories as $k => $v ) {
echo $k; echo "<br/>";
}
if you wants to get category id which exits in $input_category then user this
$flipped = array_flip($categories);
foreach ( $input_categories as $v ) {
echo $flipped[$v]; echo "<br/>";
}

PHP sort array by key 'value'

I have the following code which displays the results that I want. I'm trying to get it to sort on the key 'value' from the output below. So Eric, Eric 2, Eric 3
An example output of $resultnames is:
Array
(
[0] => Array
(
[Eric 2] => Asdf
)
[1] => Array
(
[Eric] => Asdf
)
[2] => Array
(
[Eric 3] => Asdf
)
)
So the key is the first name and the value of that key is the last name. I'm trying to sort the array by first name
foreach (array_chunk($uvugroups, 6, true) as $uvugroup)
{
foreach ($uvugroup as $uvustate) {
echo "<h4>Registrants</h4>";
$fnames = explode( '|', $uvustate['fname'] );
$lnames = explode( '|', $uvustate['lname'] );
$resultnames = array();
foreach ($fnames as $i => $key) {
$resultnames[] = array($key => $lnames[$i]);
}
foreach ($resultnames as $resultname) {
foreach ($resultname as $fkey => $lkey) {
echo "<ul>";
echo "<li>" . $fkey . " " . substr($lkey,0,1) . ".</li>";
echo "</ul>";
}
}
}
}
I tried to use ksort in different places in the code, but it didn't seem to have an effect.
It's a bit hard because the expected output is not defined in the question, but with this code as the contents of the second foreach it should produce a list sorted by first name.
$fnames = explode( '|', $uvustate['fname'] );
$lnames = explode( '|', $uvustate['lname'] );
$resultnames = array_combine($fnames, $lnames);
ksort($resultnames);
echo "<ul>";
foreach ($resultnames as $fkey => $lkey) {
echo "<li>" . $fkey . " " . substr($lkey,0,1) . ".</li>";
}
echo "</ul>";

Loop in subset of an array matching key text in PHP

I have this array (using PHP):
Array
(
[dummy_value_01] => 10293
[other_dummy_value_01] => Text
[top_story_check] => 1
[top_story_hp] => 1
[top_story] => 248637
[top_story_id] => 100
[top_story_text] => 2010
[menu_trend_01] => 248714
[menu_trend_01_txt] => Text 01
[menu_trend_02] => 248680
[menu_trend_02_txt] => Text 02
[menu_trend_03] => 248680
[menu_trend_03_txt] => Text 03
[menu_trend_04] => 248680
[menu_trend_04_txt] => Text 04
[menu_trend_05] => 248680
)
I would like to loop only the menu_trend_* values and obtain a list like this:
<ul>
<li>Text 01: 248714</li>
<li>Text 02: 248680</li>
<li>[...]</li>
</ul>
Could you suggest the best way?
You can use this, it will try to match menu_trend_(DIGIT) and if it does, will echo the needed text.
echo '<ul>';
foreach ($array as $key => $val) {
$matches = array();
if (!preg_match('/^menu_trend_(\d+)$/', $key, $matches)) {
continue;
}
echo sprintf('<li>Text %s: %s</li>', $matches[1], $val);
}
echo '</ul>';
I'm not certain that this is the best way, but it will work:
$output = array();
foreach ($array as $k => $a) {
if (stristr($k, 'menu_trend_') && !empty($arr[$k . '_txt'])) {
$output[] = $arr[$k . '_txt'] . ': ' . $a;
}
}
echo "<ul>\n<li>" . implode("</li>\n<li>", $output) . "</li>\n</ul>";
Here's a working example

PHP compare values in a single array and output the difference

I have an array that looks like this:
$rowarray(
[0] => [PID] => 97162 [TID] => 340 [StatsID] => 49678
[1] => [PID] => 97165 [TID] => 340 [StatsID] => 49673
[2] => [PID] => 97167 [TID] => 340 [StatsID] => 49675
[3] => [PID] => 97162 [TID] => 340 [StatsID] => 49679
)
Then my code looks like this:
$cntr=0;
foreach($rowarray as $row)
{
echo "<tr><td>$row[PID] $row[TID] $row[StatsID] </td></tr>";
$cntr++;
}
Two things I want to do I want to be able not print the duplicates in the array but print the additional column that has a different value. So my desired output would look like this.
97162 340 49678 49679
97165 340 49673
97167 340 49675
I started out with the array_unique() but that only returned:
97162 340 49678
Assuming only the StatsID changes (not clear from the question)
$map = array();
foreach($rowarray as $row){
$k = $row["PID"] . '-' . $row["TID"];
if( !isset( $map[$k] ) ){
$map[$k] = array();
}
array_push( $map[$k], $row["StatsId"] );
}
foreach($map as $k=>$v){
$row = explode( '-', $k );
echo "<tr><td>$row[0] $row[1] " . implode( " ", $v ) . " </td></tr>";
}
Here's what I'd do:
Start by sorting the array (using usort to sort by PID, then by TID)
Initialize "last" variables ($last_PID and $last_TID). They will store the respective values in the loop
In the loop, first compare the "current" variables to the "last" ones, if they're the same then just echo the StatsID value.
If they're not the same, output the <tr> (but not the final </tr>, so the first part of the loop can add more StatsID values if necessary)
Still inside the loop, after outputting everything, update the "last" variables.
After the loop, output the final </tr>
This may not be optimal, but I'm pretty sure it'll work.
Transfer the $rowarray structure into a map of maps of arrays, like this:
$rowarray = array(
array('PID' => 97162, 'TID' => 340, 'StatsID' => 49678),
array('PID' => 97165, 'TID' => 340, 'StatsID' => 49673),
array('PID' => 97167, 'TID' => 340, 'StatsID' => 49675),
array('PID' => 97162, 'TID' => 340, 'StatsID' => 49679)
);
$keys = array();
foreach ($rowarray as $row) {
if (!is_array(#$keys[$row['TID']])) {
$keys[$rowarray['TID']] = array();
}
if (!is_array(#$keys[$row['TID']][$row['PID']])) {
$keys[$row['TID']][$row['PID']] = array();
}
$keys[$row['TID']][$row['PID']][] = $row['StatsID'];
}
foreach ($keys as $pid => $pid_arr) {
foreach ($pid_arr as $tid => $tid_arr) {
echo "<tr><td>$tid $pid " . implode(' ', $tid_arr) . "</td></tr>";
}
}
See this code in action
As far as I can tell, the only way to do this would be to loop through the array creating a new unique array as you go.
$unique = array();
foreach ($row as $value)
{
$key = $value['PID'];
if (isset($unique[$key]))
{
$unique[$key]['StatsID'] .= ' ' . $value['StatsID'];
}
else
{
$unique[$key] = $value;
}
}
Now, $unique would give you the results you're looking for and you can loop through the unique array and output your results (I also added your counter if needed):
$count = count($unique);
foreach ($unique as $row)
{
echo "<tr><td>{$row['PID']} {$row['TID']} {$row['StatsID']} </td></tr>";
}

Categories