I have this result inside my foreach loop:
Tonsilitis
Tonsilitis
Laryngitis
Rhinosinusitis Akut
Rhinosinusitis Akut
Rhinosinusitis Akut
Common Cold
Common Cold
Common Cold
Rhinitis Alergi
This is my script:
foreach ($results as $data) :
$final = $data->nama_diagnosis . '<br>';
echo $final;
endforeach;
My question is, how can i count the same word in my loop or outside the loop. Can i do that? give me the solution please. As a result i want to count them like this:
Tonsilitis = 2
Laryngitis = 1
Rhinosinusitis Akut = 3
Common Cold = 3
Rhinitis Alergi = 1
Or maybe i can filter the same word so i get only the most words, like Rhinosinusitis Akut and Common Cold. Please help me.
Thanks
You can try something like this, iterating through array with foreach loop and using a ternary operator with isset to safely assign and increment each occurrence:
$count = array();
foreach ($results as $result)
isset($count[$data]) ? $count[$data]++ : $count[$data] = 1;
Example
In foreach loop save words and their count into array, then make another loop and write the amounts.
<?php
$results = array(
array('nama_diagnosis' => 'Tonsilitis'),
array('nama_diagnosis' => 'Tonsilitis'),
array('nama_diagnosis' => 'Laryngitis'),
array('nama_diagnosis' => 'Rhinosinusitis Akut'),
array('nama_diagnosis' => 'Rhinosinusitis Akut'),
array('nama_diagnosis' => 'Rhinosinusitis Akut'),
array('nama_diagnosis' => 'Common Cold'),
array('nama_diagnosis' => 'Common Cold'),
array('nama_diagnosis' => 'Common Cold'),
array('nama_diagnosis' => 'Rhinitis Alergi')
);
$res = array();
foreach ($results as $words) { // changed $word to $words
foreach ($words as $word) { // this foreach added
if (isset($res[$word])) {
$res[$word] += 1;
} else {
$res[$word] = 1;
}
} // end of nested foreach which was added
}
foreach ($res as $word => $count) {
echo $word . ' (' . $count . ')<br>';
}
/*
output:
Tonsilitis (2)
Laryngitis (1)
Rhinosinusitis Akut (3)
Common Cold (3)
Rhinitis Alergi (1)
*/
?>
Try with -
$counts = array();
foreach ($results as $data) :
$final = $data->nama_diagnosis . '<br>';
if (array_key_exists($data->nama_diagnosis, $counts)) {
$counts[$data->nama_diagnosis] += 1;
} else {
$count[$data->nama_diagnosis] = 1;
}
endforeach;
foreach ($counts as $key => $val) {
echo $key.' = '.$val;
}
This should work for you:
<?php
$results = array("Tonsilitis", "Tonsilitis", "Laryngitis", "Rhinosinusitis Akut", "Rhinosinusitis Akut", "Rhinosinusitis Akut", "Common Cold", "Common Cold", "Common Cold", "Rhinitis Alergi");
$counter = array();
foreach ($results as $data):
if(in_array($data->nama_diagnosis, array_flip($counter)))
$counter[$data->nama_diagnosis]++;
else
$counter[$data->nama_diagnosis] = 1;
endforeach;
foreach ($counter as $key => $data)
echo $key . " = " . $data . "<br />";
?>
Output:
Tonsilitis = 2
Laryngitis = 1
Rhinosinusitis Akut = 3
Common Cold = 3
Rhinitis Alergi = 1
Related
I have an array like this:
$aMyArray = array(
"bmw"=>"user1",
"audi"=>"user2",
"mercedes"=>"user3"
);
And I only want to show the first two elements bmw=>user1 and audi=>user2.
But I want it by using a foreach loop.
If you want the first 2 by name:
Using in_array (documentation) is what you looking for:
$aMyArray = array("bmw"=>"user1", "audi"=>"user2", "mercedes"=>"user3");
$valuesToPrint = array("bmw", "audi");
foreach($aMyArray as $key => $val) {
if (in_array($key, $valuesToPrint))
echo "Found: $key => $val" . PHP_EOL;
}
If you want the first 2 by index use:
init index at 0 and increment in each iteration as:
$aMyArray = array("bmw"=>"user1", "audi"=>"user2", "mercedes"=>"user3");
$i = 0;
foreach($aMyArray as $key => $val) {
echo "Found: $key => $val" . PHP_EOL;
if (++$i > 1)
break;
}
$counter = 1;
$max = 2;
foreach ($aMyArray as $key => $value) {
echo $key, "=>", $value;
$counter++;
if ($counter === $max) {
break;
}
}
It is important to break execution to avoid arrays of any size looping until the end for no reason.
<?php
$aMyArray = array(
"bmw"=>"user1",
"audi"=>"user2",
"mercedes"=>"user3"
);
reset($aMyArray);
echo key($aMyArray).' = '.current($aMyArray)."\n";
next($aMyArray);
echo key($aMyArray).' = '.current($aMyArray)."\n";
Easiest way:
$aMyArray=array("bmw"=>"user1","audi"=>"user2","mercedes"=>"user3");
$i=0;
foreach ($aMyArray as $key => $value) {
if($i<2)
{
echo $key . 'and' . $value;
}
$i++;
}
I know you're asking how to do it in a foreach, but another option is using array travelling functions current and next.
$aMyArray = array(
"bmw"=>"user1",
"audi"=>"user2",
"mercedes"=>"user3"
);
$keys = array_keys($aMyArray);
//current($array) will return the value of the current record in the array. At this point that will be the first record
$first = sprintf('%s - %s', current($keys), current($aMyArray)); //bmw - user1
//move the pointer to the next record in both $keys and $aMyArray
next($aMyArray);
next($keys);
//current($array) will now return the contents of the second element.
$second = sprintf('%s - %s', current($keys), current($aMyArray)); //audi - user2
You are looking for something like this
$aMyArray = array(
"bmw"=>"user1",
"audi"=>"user2",
"mercedes"=>"user3"
);
foreach($aMyArray as $k=>$v){
echo $v;
if($k=='audi'){
break;
}
}
I've got this array:
Array
(
[0] => Array
(
[name] => System
[order] => 1
[icon] => stats.svg
[0] => Array
(
[title] => Multilingual
)
[1] => Array
(
[title] => Coloring
)
[2] => Array
(
[title] => Team work
)
[3] => Array
(
[title] => Tutorials
)
)
)
I want to loop into this to show the section name and after all the features containing in the following array.
So, this is what I made:
foreach ($features as $feature => $info) {
echo '
'.$info['name'].'
<ul class="menu-vertical bullets">
';
foreach (array_values($info) as $i => $key) {
echo '
<li>'.$key['title'].'</li>
';
}
echo '
</ul>
';
}
It works except for the first third <li> where I have the first char of name, order and icon value.
Do you know why ?
Thanks.
array_values return value of array so for info values is name, order, icon, 0, 1, ...
Your values foreach is wrong if you just want print title you can use:
foreach ($features as $feature => $info) {
echo '
'.$info['name'].'
<ul class="menu-vertical bullets">
';
//Remove some keys from info array
$removeKeys = array('name', 'order', 'icon');
$arr = $info;
foreach($removeKeys as $key) {
unset($arr[$key]);
}
foreach (array_values($arr) as $i => $key) {
echo '
<li>'.$key['title'].'</li>
';
}
echo '
</ul>
';
}
In php, array_values means all the values of the array. So array_values($info) is array($info['name'], $info['order'], $info['icon'], $info[0], $info[1], $info[2], $info[3])
in your example, you can skip the non-integer keys of the $info to get your titles:
<?php
$features = array();
$info = array();
$info['name'] = 'System';
$info['order'] = 1;
$info['icon'] = 'stats.svg';
$info[] = array('title'=>'Multilingual');
$info[] = array('title'=>'Coloring');
$features[] = $info;
foreach ($features as $feature => $info) {
echo $info['name'] . PHP_EOL;
echo '<ul class="menu-vertical bullets">' . PHP_EOL;
foreach ($info as $k => $item) {
if(!is_int($k)) continue;
echo '<li>' . $item['title'] . '</li>' . PHP_EOL;
}
echo '</ul>' . PHP_EOL;
}
BUT, your original data structure is not well designed and hard to use. For a better design, you can consider the following code, move your items to a sub array of $info:
<?php
$features = array();
$info = array();
$info['name'] = 'System';
$info['order'] = 1;
$info['icon'] = 'stats.svg';
$info['items'] = array();
$info['items'][] = array('title'=>'Multilingual');
$info['items'][] = array('title'=>'Coloring');
$features[] = $info;
foreach ($features as $feature => $info) {
echo $info['name'] . PHP_EOL;
echo '<ul class="menu-vertical bullets">' . PHP_EOL;
foreach ($info['items'] as $item) {
echo '<li>' . $item['title'] . '</li>' . PHP_EOL;
}
echo '</ul>' . PHP_EOL;
}
Sample output of the two demos:
System
<ul class="menu-vertical bullets">
<li>Multilingual</li>
<li>Coloring</li>
</ul>
It works except for the first third li where I have the first char of name, order and icon value. Do you know why ?
Why you see first chars of the values of 'name', 'order', 'icon'? Let see how PHP works.
Take the first loop as an example: foreach (array_values($info) as $i => $key)
Then $i == 0, $key == 'System'
We know that $key[0] == 'S', $key[1] == 'y', $key[2] == 's', etc.
Then you try to access $key['title'], but the string 'title' is not valid as a string offset, so it is converted to an integer by PHP: intval('title') == 0.
Then $key['title'] == $key[intval('title')] == 'S'
That's what you see.
array_value() returns the values of the array, here you will get the value of the array $info and what I understand is that is not what you need. See details for array_value().
You can check if the key for the $info is an integer. if yes, echo the title. Give this a try.
foreach ($features as $feature => $info) {
echo $info['name'].'<ul class="menu-vertical bullets">';
foreach ($info as $key => $value) {
if (is_int($key)) {
echo '<li>'.$key['title'].'</li>';
}
}
echo '</ul>';
}
I am trying to get my head around arrays.
The arrays should look like this:
$questions[$a] => array( [0] => No, comment1
[1] => Yes, comment2
[2] => No, comment3 )
$answer[$a] => array( [0] => No
[1] => Yes
[3] => No )
$comment[$a] => array( [0] => comment1
[1] => comment2
[3] => comment3 )
=========================================================================
SECOND EDIT: Need to execute this in the loop to create a third array -
if($answer[$a] == "Yes") { $display[$a] = "style='display:none'";
} else { $display[$a] = "style='display:block'"; }
This is what i have: (28th for minitech)
while ($a > $count)
{
if($count > 11) {
foreach($questions as $q) {
list($answer, $comments[]) = explode(',', $q);
if($answer === "Yes") {
$display[$a] = "style='display:none'";
} else {
$display[$a] = "style='display:block'";
}
$answers[] = $answer;
}
}
$a++;
}
If they are actually strings, explode works:
$answers = array();
$comments = array();
$display = array();
foreach(array_slice($questions, 11) as $question) {
list($answer, $comments[]) = explode(',', $question);
$display[] = $answer === 'Yes' ? 'style="display: none"' : 'style="display: block"';
$answers[] = $answer;
}
Here’s a demo!
Change your while loop to this
while ...
{
$parts = explode(',', $questions[$a]);
$answer[$a][] = trim($parts[0]);
$comment[$a][] = trim($parts[1]);
}
In your original code you were overwriting the $answer[$a] and $comment[$a] each time, not appending to the end of an array
$questions[$a] = array('Q1?' => 'A1', 'Q2?' => 'A2', 'Q3?' => 'A3');
foreach($questions[$a] as $key => $value)
{
$comment[$a][] = $key;
$answer[$a][] = $value;
}
This should work.
foreach ($questions[$a] as $key=>$value){
$temp = explode(',',$value);
$answer[$key] = $temp[0];
$comment[$key] = $temp[1];
}
$key will have 0,1,2 respectively. $value will have the values for each $question[$a](No,Comment1 ....)
Can't think of a funky one-liner, but this should do it:
foreach ($questions as $a => $entries) {
foreach ($entries as $k => $entry) {
$parts = array_map('trim', explode(',', $entry));
$answer[$a][$k] = $parts[0];
$comment[$a][$k] = $parts[1];
}
}
$questions = array( 0 => 'No,comment1',1 => 'Yes,comment2',2 => 'No,comment3' );
foreach($questions as $question)
{
$parts = explode(",",$question);
$answer[] = $parts[0];
$comment[] = $parts[1];
}
echo "<pre>";
print_r($answer);
print_r($comment);
Here is the right answer
foreach($questions as $key => $question){
foreach($question as $q => $data){
$data= explode(',',$data);
$comments[$key][$q] = $data[0];
$answer[$key][$q] = $data[1];
}
}
If the values in $questions are comma-separated strings you could use an array_walk function to populate your $answer and $comment arrays
$question = array(...); //array storing values as described
$answer = array();
$comment = array();
array_walk($question, function ($value, $key) use ($answer,$comment) {
$value_array = explode(',', $value);
$answer[$key] = $value_array[0];
$comment[$key] = $value_array[1];
});
Note that this is shown using an anonymous function (closure) which requires PHP >= 5.3.0. If you had a lower version of PHP, you would need to declare a named function, and declare $answer and $comment as globals in the function. I think this is a hacky approach (using globals like this) so if I was using PHP < 5.3 I would probably just use a foreach loop like other answers to your question propose.
Functions like array_walk, array_filter and similar functions where callbacks are used are often great places to leverage the flexibility provided by anonymous functions.
How to echo out the values individually of this array?
Array ( [0] => 20120514 [1] => My Event 3 )
so
echo $value[0]; etc
I have this so far:
foreach (json_decode($json_data_string, true) as $item) {
$eventDate = trim($item['date']);
// positive limit
$myarray = (explode(',', $eventDate, 2));
foreach ($myarray as $value) {
echo $value;
}
This echo's out the whole string no as an array. and if i do this?
echo $value[0};
Then I only get 2 characters of it??
The print_r :
Array ( [0] => 20120430 [1] => My Event 1 )
foreach ($array as $key => $val) {
echo $val;
}
Here is a simple routine for an array of primitive elements:
for ($i = 0; $i < count($mySimpleArray); $i++)
{
echo $mySimpleArray[$i] . "\n";
}
you need the set key and value in foreach loop for that:
foreach($item AS $key -> $value) {
echo $value;
}
this should do the trick :)
The problem here is in your explode statement
//$item['date'] presumably = 20120514. Do a print of this
$eventDate = trim($item['date']);
//This explodes on , but there is no , in $eventDate
//You also have a limit of 2 set in the below explode statement
$myarray = (explode(',', $eventDate, 2));
//$myarray is currently = to '20'
foreach ($myarray as $value) {
//Now you are iterating through a string
echo $value;
}
Try changing your initial $item['date'] to be 2012,04,30 if that's what you're trying to do. Otherwise I'm not entirely sure what you're trying to print.
var_dump($value)
it solved my problem, hope yours too.
I have a multidimensional array in PHP, something that looks like:
array(array(Category => Video,
Value => 10.99),
array(Category => Video,
Value => 12.99),
array(Category => Music,
Value => 9.99)
)
and what I would like to do is combine similar categories and output everything into a table, so the output would end up being:
<tr><td>Video</td><td>23.98</td></tr>
<tr><td>Music</td><td>9.99</td></tr>
Any suggestions on how to do this?
EDIT:
I can have these in two different arrays if that would be easier.
A simple loop will do:
$array = [your array];
$result = array();
foreach ($array as $a) {
if (!isset($result[$a['Category']])) {
$result[$a['Category']] = $a['Value'];
} else {
$result[$a['Category']] += $a['Value'];
}
}
foreach ($result as $k => $v) {
echo '<tr><td>' . htmlspecialchars($k) . '</td><td>' . $v . '</td></tr>';
}
$result = array();
foreach ($array as $value) {
if (isset($result[$value['Category']])) {
$result[$value['Category']] += $value['Value'];
} else {
$result[$value['Category']] = $value['Value'];
}
}
foreach ($result as $category => $value) {
print "<tr><td>$category</td><td>$value</td></tr>";
}