PHP Place text (title) before each array category - php

This function is supposed to echo all singles and doubles numbers. (eg. 01 - 01 02).
I am trying to place a title before each 'category' using the code below and it is not working properly.
It should be something like this
SINGLES
01,02,03
DOUBLES
01 02, 03 04, 05 06
Can you help me fix this? Thanks!
function check_stats($todas){
$arrlength = count($todas);
for($x = 0; $x < $arrlength; $x++) {
$arrlength2 = count($todas[$x]);
if($arrlength2==1){
echo 'single'.'</br></br>';
list($a) = explode(" ", implode(" ", $todas[$x]));
echo $a; echo '</br>';
}
if($arrlength2==2){
echo 'double'.'</br></br>';
list($a,$b) = explode(" ", implode(" ", $todas[$x]));
echo $a.' '.$b; echo '</br>';
}
} //for
} //function

You are trying to separate singles and doubles. And you want to print them separately. You can't print them separately while you haven't detected them all. Then you need to detect all categories and after that you can print them separately. To do this you should save categories on detection and after detection print saved categories.
function check_stats($todas){
$singles = array(); // an array to save single numbers
$doubles = array(); // an array so save doubles
foreach ($todas as $toda) { // cleaner and beautifier than for
if (count($toda) == 1) { // direct compare without extra $arrlength2
$singles[] = $toda[0]; // will push $toda[0] to $singles array
} else if (count($toda) == 2) { // when put else compares less
$doubles[] = $toda[0] . ' ' . $toda[1];
}
}
// then you can do whatever with $singles and $doubles
echo 'SINGLES' . PHP_EOL;
foreach ($singles as $single) {
echo $single . PHP_EOL;
}
echo 'DOUBLES' . PHP_EOL;
foreach ($doubles as $double) {
echo $double . PHP_EOL;
}
}
Edit #1:
If there were more than 2 kind of variables, then you can keep them in an array.
function check_stats($todas){
$result_array = array();
foreach ($todas as $toda) {
$result_array[count($toda)] = implode(' ', $toda);
// the above code will save each single or double or triple or etc
// in an index in their size
}
return $result_array; // better return it and use out of function
}
$result = check_stats($todas);
// now print them
foreach ($todas as $key => $toda) {
echo $key . PHP_EOL; // print count (that is index)
foreach ($toda as $t) {
echo $t . PHP_EOL;
}
}

Related

How to count/sum this values of the same word in PHP?

I am confused to count these words,
I've some data like this :
web = 1
sistem=1
web=1
sistem=1
web=1
sistem=1
sistem=0
sistem=0
web=0
sistem=0
web=0
sistem=0
web=0
web=0
I want to make result like this :
web = 3
sistem = 3
I'm using array_count_values(), but this result is not good
Array ( [web=1] => 3 [sistem=1] => 3 [sistem=0] => 4 [web=0] => 4 )
My code like this :
foreach ($g as $key => $kata) {
if (strpos($cleanAbstrak, $kata)) {
echo $kata . $ada . "<br>";
$p[] = $kata . "=" . $ada;
// print_r($p);
echo "<br><br>";
} else {
echo $kata, $tidak . "<br>";
$q[] = $kata . "=" . $tidak;
// $m = explode(" ", $q);
// print_r($q);
// echo $q . '<br>';
echo "<br><br>";
}
}
$s = array_merge($p, $q);
echo "<br><br>";
print_r($s);
echo "<br>";
$f = array_count_values($s);
// print_r($f);
echo "<br><br>";
thank you very much if you are willing to help me
RESULT THIS CODE
Another simple way is use a counter like that:
$web=0;
$sistem=0;
foreach ($g as $key => $kata) {
if (strpos($cleanAbstrak, $kata)) {
$sistem=$sistem + $ada;
} else {
$web=$web+$tidak
}
}
echo 'web='.$web.'<br> sistem='.$sistem;
First, you need to separate word and value.
Second, you need to check the value : if it's zero you let it go (can't hold it back anymore). Else you count the value ; if it's written, i suppose it can be greater than 1 ; if it's not, it should be "word", or nothing (which would greatly facilitate counting).
Something like
<?php
$tab = [
'web=1',
'sistem=1',
'web=1',
'sistem=1',
'web=1',
'sistem=1',
'sistem=0',
'sistem=0',
'web=0',
'sistem=0',
'web=0',
'sistem=0',
'web=0',
'web=0',
];
$tab_clean = [];
foreach($tab as $item) {
preg_match('/([a-z]+)=([\d]+)/', $item, $matches);
//print_r($matches);
$word = $matches[1];
$number = $matches[2];
for($i = 0; $i < $number; $i++) {
$tab_clean[] = $word;
}
}
$tab_count = array_count_values($tab_clean);
print_r($tab_count);
?>

Inserting count and sum functions

Here is what my code prints:
Even numbers: 2 4 6
Here is my PHP code:
$names = file('file.txt');
echo "Text: ";
foreach($names as $name)
{
echo $name . "</br>";
}
echo "Even numbers: ";
foreach ($names as $name) {
$name = count_chars( $name, 3);
for($i=0; $i<strlen($name);$i++) {
if (is_numeric($name[$i]) && $name[$i]%2==0)
{
echo $name[$i];
}
}
echo "<br>";
}
?>
Could someone tell me how should I count all of these values into the new line (I need to get an answer 3) and get those values sum (I need to get 12)? I know I have to use count and sum functions, i don't know exactly where. Thanks for any help. All the answer should look like this:
Even numbers: 2 4 6
Even numbers are: 3
Even numbers sum are: 2 + 4 + 6 = 12
I don't really understand what your question.
But I think array_sum is what you are looking for. (https://secure.php.net/manual/en/function.array-sum.php)
Below is my code for your reference:
$array = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
foreach($array as $key => $value) {
if (empty($value%2)) {
$even[] = $value;
} else {
$odd[] = $value;
}
}
echo 'Even numbers: '.implode(' ', $even).'<br>';
echo 'Odd numbers: '.implode(' ', $odd).'<br>';
echo 'Even numbers sum are: '.implode(' + ', $even).' = '.array_sum($even);
Try this :
$names = file('file.txt');
echo "Text: ";
foreach($names as $name)
{
echo $name . "</br>";
}
echo "Even numbers: ";
foreach ($names as $name) {
$count = 0
$evens = [];
$name = count_chars($name, 3);
for($i=0; $i<strlen($name);$i++) {
if (is_numeric($name[$i]) && $name[$i]%2==0)
{
$count++;
$evens[] = $name[$i];
echo $name[$i];
}
}
echo "<br>";
}
echo "Even numbers Are: " . $count;
$i=0;
foreach($evens as $e){
$i++;
if($i == count($evens)){
$evens_string .= $e . '=' ;
} else {
$evens_string .= $e . '+' ;
}
}
$even_string .= array_sum($evens);
echo "Even numbers sum are: " . $even_string;
Hope this gives you the idea! I have not tested the code.

How to order by a segment of preg_match_all results?

I'm using PHP to generate a list of references to a text by doing a preg_match_all search on a database table. Here is the PHP code:
$query = "SELECT primary_tag,display_short_title,content FROM topics;";
$result = mysql_query($query) or die("Query failed : " . mysql_error());
$num_results = mysql_num_rows($result);
for ($i = 0; $i < $num_results; $i++) {
$row = mysql_fetch_array($result);
if (preg_match_all("/(\<i\>U\<\/i\>|U) [0-9]{1,2}\.[0-9]{1,7}/", $row["content"], $matches)) {
foreach ($matches[0] as $match) {
$match = ltrim(strip_tags($match), "U ");
echo '<p class="textmark_result">' . $match;
echo ' ' . $row["display_short_title"] . '';
echo "</p>\n";
}
}
}
And the results (viewing source) look like this:
<p class="textmark_result">15.1737 Medicine</p>
<p class="textmark_result">5.678 Science</p>
<p class="textmark_result">14.665 Science</p>
In the resulting web page, I want to order the results by the decimal in the middle, the $match in the code, so that (in this example) 5.678 comes first, then 14.665, then 15.1737. Is there a way to do that?
Thank you!
Three steps to do:
Get all your matches and add them to an array - floatval($match) is the key.
Sort the resulting array by key (floats sort by numeric value, strings sort by characters - therefore floatval(...)).
Iterate on the sorted array
Code:
// MySQL stuff goes here ...
// create empty array
$results = array();
for ($i = 0; $i < $num_results; $i++) {
$row = mysql_fetch_array($result);
if (preg_match_all("/(\<i\>U\<\/i\>|U) [0-9]{1,2}\.[0-9]{1,7}/", $row["content"], $matches)) {
foreach ($matches[0] as $match) {
$match = ltrim(strip_tags($match), "U ");
// array pseudo key is the float value of $match
// add '_key' member for usort()
$row['_key'] = floatval($match);
$results[] = $row;
}
}
}
// sort the array by the float key
usort($results, function($a, $b) {
if($a['_key'] == $b['_key']) return 0;
elseif($a['_key'] > $b['_key']) return 1;
else return -1;
});
// ... then display stuff in order
foreach($results as $row) {
echo '<p class="textmark_result">' . (string)$row['_key'];
echo ' <a href="../Essays/topic.php?shorttitle='
. $row["primary_tag"] . '">' . $row["display_short_title"] . '</a>';
echo "</p>\n";
}

To get the multi dimention array values in php

I have a multi-dimension array in php like this
$shop = array(
array("name","point","number"),
array('Ranjit', 1.25 , 15),
array('Pitabas', 0.75 , 25),
array('Khela', 1.15 , 7)
);
Now I have to show the output like this
name-> ranjit
Point-> 1.25
number->15
name->Pitabas
Point->0.75
number->25
name->Khela
Point->1.15
number->7
I am trying for loop, but I could get the result in nested forloop. Please help me to get the answer.
My solution:
$headings = array_shift($shop);
foreach ($shop as $item) {
foreach ($item as $key => $value) {
echo $headings[$key], '=>', $value;
}
}
Here's a simple loop: Observe that we skip the first element of the outer array, which is deemed to contain the headers:
for ($i = 1; $i != count($shop); ++$i)
{
print $shop[0][0] . ": ". $shop[$i][0] . "\n";
print $shop[0][1] . ": ". $shop[$i][1] . "\n";
print $shop[0][2] . ": ". $shop[$i][2] . "\n";
}
You know the first row will be the titles, so store them separately:
$titles = $shop[0];
That will give you
$titles = array('name', 'point', 'number');
Then loop through your array:
foreach ($shop as $index => $row) {
if ($index == 0)
continue;
foreach($row as $column => $item) {
echo $titles[$column] . " -> " . $item . "<br />";
}
}
This should give the desired output:
for($x = 1, $lim = sizeof($shop); $x < $lim; $x++)
{
echo $shop[0][0]."->".$shop[$x][0]."<br>";
echo $shop[0][1]."->".$shop[$x][1]."<br>";
echo $shop[0][2]."->".$shop[$x][2]."<br>";
}

Create a comma-separated string from a single column of an array of objects

I'm using a foreach loop to echo out some values from my database, I need to strip the last comma from the last loop if that makes sense.
My loop is just simple, as below
foreach($results as $result){
echo $result->name.',';
}
Which echos out
result,result,result,result,
I just need to kill that pesky last comma.
Better:
$resultstr = array();
foreach ($results as $result) {
$resultstr[] = $result->name;
}
echo implode(",",$resultstr);
1. Concat to string but add | before
$s = '';
foreach ($results as $result) {
if ($s) $s .= '|';
$s .= $result->name;
}
echo $s;
2. Echo | only if not last item
$s = '';
$n = count($results);
foreach ($results as $i => $result) {
$s .= $result->name;
if (($i+1) != $n) $s .= '|';
}
echo $s;
3. Load to array and then implode
$s = array();
foreach ($results as $result) {
$s[] = $result->name;
}
echo implode('|', $s);
4. Concat to string then cut last | (or rtrim it)
$s = '';
foreach ($results as $result) {
$s .= $result->name . '|';
}
echo substr($s, 0, -1); # or # echo rtrim($s, '|');
5. Concat string using array_map()
echo implode('|', array_map(function($result) { return $result->name; }, $results));
$result_names = '';
foreach($results as $result){
$result_names .= $result->name.',';
}
echo rtrim($result_names, ',');
I've been having the same issue with this similar problem recently. I fixed it by using an increment variable $i, initializing it to 0, then having it increment inside the foreach loop. Within that loop place an if, else, with the echo statement including a comma if the $i counter is less than the sizeof() operator of your array/variable.
I don't know if this would fix your issue per se, but it helped me with mine. I realize this question is years-old, but hopefully this will help someone else. I'm fairly new to PHP so I didn't quite understand a lot of the Answers that were given before me, though they were quite insightful, particularly the implode one.
$i=0;
foreach ($results as $result) {
$i++;
if(sizeof($results) > $i) {
echo $result . ", ";
} else {
echo $result;
}
}
In modern PHP, array_column() will allow you to isolate a column of data within an array of objects.
Code: (Demo)
$results = [
(object)['name' => 'A'],
(object)['name' => 'B'],
(object)['name' => 'C']
];
echo implode(',', array_column($results, 'name'));
Output:
A,B,C
That said, since you are iterating a result set, then you may be better served by calling a CONCAT() function in your sql, so that the values are already joined in the single value result set.
If you are processing a collection in Laravel, you can pluck() and implode():
$collection->pluck('name')->implode(',')
$arraySize = count($results);
for($i=0; $i<$arraySize; $i++)
{
$comma = ($i<$arraySize) ? ", " : "";
echo $results[$i]->name.$comma;
}
Not as pretty, but also works:
$first=true;
foreach($results as $result){
if(!$first) { echo ', '; }
$first=false;
echo $result->name;
}
Another smart way is:
foreach($results as $result){
echo ($passed ? ',' : '') . $result->name;
$passed = true;
}
In this case at first loop $passed is NULL and , doesn't print.
I know this is an old thread, but this came up recently and I thought I'd share my alternate, cleaner way of dealing with it, using next().
$array = array("A thing", "A whatsit", "eighty flange oscillators");
foreach( $array as $value ){
echo $value;
$nxt = next($array);
if($nxt) echo ", "; // commas between each item in the list
else echo ". And that's it."; // no comma after the last item.
}
// outputs:
// A thing, A whatsit, eighty flange oscillators. And that's it.
play with it here
I have to do this alot because I'm always trying to feed numbers in to jplot, I find its easier to put the comma in the front of the loop like so:
foreach($arrayitem as $k){ $string = $string.",".$k;
}
and then chop off the first character (the comma) using substr, it helps if you know a guestimate of long your string will be, I'm not sure what the limit on substr max character is.
echo substr($a,1,10000000);
hope this helps.
$a[0] = 'John Doe';
$a[1] = 'Jason statham';
$a[2] = 'Thomas Anderson';
$size = count($a);
foreach($a as $key=>$name){
$result .= $name;
if($size > $key+1) $result .=', ';
}
echo $result;
<?php
$return = array(any array)
$len = count($return);
$str = '';
$i = 1;
foreach($return as $key=>$value)
{
$str .= '<a href='.$value['cat_url'].'>'.$value['cat_title'].'</a>';
if($len > $i)
{
$str .= ',';
$i = $i+1;
}
}
echo $str;
?>
<?php
$i = 1;
$count = count( $results );
foreach( $results as $result ) {
echo $result->name;
if ( $i < $count ) echo ", ";
++$i;
}
?>
This is what I normally do, add a comma before the item rather than after, while ignoring the first loop.
$i = 0;
$string = '';
foreach($array as $item){
$string .= ($i++ ? ',' : '').$item;
}
First get all the output by using output buffering. Then, trim the comma and display it. So, do it like this:
ob_start();
foreach($results as $result)
{
echo $result->name.',';
}
$output = ob_get_clean();
echo rtrim($output, ',');
The output buffering method helps if the inside loop is very big (and OP is posting here just for brevity), then using OB is easier without changing the internals of the loop.

Categories