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>";
}
Related
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);
?>
This is part of the working code that shows the entire array;
$files = filelist("./",1,1); // call the function
shuffle($files);
foreach ($files as $list) {//print array
echo "<h4> " . $list['name'] . " </h4>";
// echo "Directory: " . $list['dir'] . " => Level: " . $list['level'] . " => Name: " . $list['name'] . " => Path: " . $list['path'] ."<br>";
How do I modify it so that it only displays 10 or 15 list instead of all?
Use a counter to limit the number of iterations:
$counter = 0;
foreach ($files as $list) {//print array
// your loop code here...
$counter++;
if ($counter > 10) break;
}
If you know the keys or indexes of the array you can do what KingCrunch is doing a lot faster by simple for loop
for($i=0; $i<=14; $i++) {
// echo $file[$i];
}
There is a function for it
foreach(array_slice($files, 0, 15) as $file) {
/* your code here */
}
http://php.net/array-slice
Another solution is to use array_rand() instead of shuffle() and array_chunk()
foreach (array_rand($files, 15) as $key) {
$file = $files[$key];
// Your code here
}
http://php.net/array-rand
Note, that this keeps the order of the keys (see salathes comment below).
Say I have this array
$array = array('pen' => 'blue', 'paper' => 'red', 'ink' => 'white');
When I loop through it
$string = '';
foreach ($array AS $key=>$value) {
$string .= $key . ' = ' . $value;
}
I want to get the "line number" of the element the loop is currently on.
If the loop is on "pen" I would get 1.
If the loop is on "paper" I would get 2.
If the loop is on "ink" I would get 3.
Is there an array command for this?
No. You will have to increment an index counter manually:
$string = '';
$index = 0;
foreach ($array as $key=>$value) {
$string .= ++$index . ") ". $key . ' = ' . $value;
}
Use array_values() function to extract values from array. It indexes array numerically and $key will be the index of value in loop.
$array = array('pen' => 'blue', 'paper' => 'red', 'ink' => 'white');
$array = array_values($array);
$string = '';
foreach ($array as $key => $value) {
$string .= $key + 1 . ' = ' . $value;
}
$i = 0;
foreach ($array as $key=>$value) { // For each element of the array
print("Current non-associative index: ".$i."<br />\n"); // Output the current index
$i++; // Increment $i by 1
}
Hope that helps.
If I have an array:
$array = array ( [rock] => 40, [pop] => 30, [rap] => 20 ) etc...
how can I do something like:
foreach key in $array
{
if (array_value > 30) echo "> 30:" . $array_key . "<br>";
if (array_value < 30) echo "< 30:" . $array_key . "<br>";
}
So that the result would be:
> 30:rock<br>
< 30:pop<br>
< 30:rap<br>
Thanks! I hope this makes sense...
foreach ($array as $key => $value) {
if ($value ...) echo $key...
else if ($value ...) echo $key...
...
}
deceze's answer is correct in general, but more specifically, the following code should work:
foreach ($array as $key => $value) {
if ($value > 30) {
echo '> 30:' . $key . '<br>';
} elseif ($value <= 30) { // Changed this to <= to cover the case of $value = 30
echo '< 30:' . $key . '<br>';
}
}
I've got a rather complicated set of loops that pulls data out of mysql and compares it to values in an array and increments a counter. When I echo a flag when the counter is incremented, I get a bijilion flags (there're like 2600 records returned from the mysql query). But each time it prints, the counters are always 1 and when I print the counter's value at the end, it shows up as zero. It seems like something is re-setting the counter…
code
# ARRAY
$demographics=array(
"region"=>array(
"Northeast"=>array('total'=>0,'consented'=>0,'completed'=>0),
//more...
"West"=>array('total'=>0,'consented'=>0,'completed'=>0)
),"societal envirn"=>array(
"Urban"=>array('total'=>0,'consented'=>0,'completed'=>0)
),"age"=>array(
'18-19'=>array('total'=>0,'consented'=>0,'completed'=>0),
'20-24'=>array('total'=>0,'consented'=>0,'completed'=>0),
//more...
'55-59'=>array('total'=>0,'consented'=>0,'completed'=>0)
),
//more...
);
# LOOPS
while ($dbrecord = mysql_fetch_assoc($surveydata)) {
foreach ( $dbrecord as $dbfield=>$dbcellval ) {
foreach ( $demographics as $demographic=>$options ) {
foreach ( $options as $option=>&$counter ) {
if($demographic==="age"){
list($min,$max) = explode('-', $option);
if ($dbcellval >= $min && $dbcellval <= $max){
$counter['total']++;
echo '$' . $option . "['total'] = " . $counter['total'] . "<br />";
if ($dbrecord['consent']==="1"){
$counter['consented']++;
echo '$' . $option . "['consented'] = " . $counter['consented'] . "<br />";
if ($dbrecord['completion status']==="complete") {
$counter['completed']++;
echo '$' . $option . "['completed'] = " . $counter['completed'] . "<br />";
break 3;
} // if
} // if
break 2;
}
} // if age
else if ($option===$dbcellval){
$counter['total']++;
echo '$' . $option . "['total'] = " . $counter['total'] . "<br />";
if ($dbrecord['consent']==="1"){
$counter['consented']++;
echo '$' . $option . "['consented'] = " . $counter['consented'] . "<br />";
if ($dbrecord['completion status']==="complete") {
$counter['completed']++;
echo '$' . $option . "['completed'] = " . $counter['completed'] . "<br />";
break 3;
} // if
} // if
break 2;
} // else if $option==$dbcellval
} // foreach $options
} // foreach $demographics
} // foreach $dbrecord
} // while
sample output
$40-44['total'] = 1
$White['total'] = 1
$35-39['total'] = 1
$Northeast['total'] = 1 // the 'total' counter is 1
$Northeast['consented'] = 1
$Northeast['completed'] = 1
$South['total'] = 1
$Northeast['total'] = 1 // notice the 'total' counter is 1 again :(
$Northeast['consented'] = 1
$Northeast['completed'] = 1
You're defining counter from a foreach instruction, as $value in foreach($foo as $key=>$value), when using the foreach you only have a local copy of $counter.
You need to use either foreach($foo as $key=>&$value) or to refer to the full array path of your counter from $demographics.
You need to reference your array at each level, otherwise you are working on a copy of the data:
foreach ( $dbrecord as $dbfield=>$dbcellval ) {
foreach ( $demographics as $demographic => &$options ) {
foreach ( $options as $option => &$counter ) {
if($demographic==="age"){
list($min,$max) = explode('-', $option);
if ($dbcellval >= $min && $dbcellval <= $max){
$counter['total']++;
What if you simply stick with the $demographics variable.
i.e.
...
foreach ( $options as $option ) {
...
$demographics[$option]['total']++;
...