Array Looping and Counting String Occurrences PHP - php

Anyone know what I'm doing wrong?
From the following array I want to count the the number of times "Friday" occurs.
Array (
[404979509517702] => Array (
[0] => 235
[1] => 04:10,Friday
)
[404045862944400] => Array (
[0] => 192
[1] => 23:52,Wednesday
)
[20403274909688162] => Array (
[0] => 186
[1] => 22:21,Tuesday
)
[202735273075459] => Array (
[0] => 336
[1] => 04:29,Tuesday
)
[652948031457462] => Array (
[0] => 410
[1] => 06:22,Monday
)
[2606749954978] => Array (
[0] => 312
[1] => 05:01,Saturday
)
[755318061725] => Array (
[0] => 384
[1] => 04:51,Friday
)
)
This is what I'm doing:
$friday = array();
foreach ($the_array as $friday){
$the_array = explode(',', $friday[1]);
$the_array[$the_array [1]] += ($friday[1]);
}
print_r($friday);
This way, I get the wrong number of "Friday" occurrences.
Any idea what I'm doing wrong or if there is a more elegant solution to that?

I would try something like the following if all you want to do is count occurrences:
$friday_count = 0;
foreach($the_array as $record) {
// Search for "Friday"
if(stristr($record[1],'Friday') !== false) {
$friday_count++; // increment count
}
}

$fridayCount = 0;
foreach ($the_array as $friday){
$friArr = explode(',', $friday[1]);
if($friArr[1] == "Friday") {
$fridayCount++;
}
}
echo ($fridayCount);

The code should be:
$fridayCount = 0;
foreach ($the_array as $friday){
if(strrpos($friday[1], 'Friday') !== false) {
$fridayCount++;
}
}
echo $fridayCount;

I think you might be complicating this unnecessarily. You should be able to test for 'Friday' and increment a counter ($friday, here) as follows:
$friday = 0;
foreach ($the_array as $element){
if (array_pop(explode(',', $element[1])) == 'Friday') {
$friday++;
}
}
echo $friday;

$cnt = 0;
foreach ($the_array as $friday){
if (explode(',', $friday[1]) == 'Friday') {
$cnt++;
}
}
echo $cnt;

Related

Set element inside array of array

If the 3rd element of array inside cars array is true i want to set others to be true .How to achieve it?
<?php
$cars = array
(
array(1,1,'f'),
array(2,2,'f'),
array(3,3,'t'),
array(4,4,'f')
);
foreach($cars as $keys){
if($keys[2]=='t')
$count=1;
}
foreach($cars as $keys){
if($count==1)
$keys[2] = 't';
}
print_r($cars);
?>
Just change 2 things as described below, Try:
$cars = array
(
array(1,1,'f'),
array(2,2,'f'),
array(3,3,'t'),
array(4,4,'f')
);
$count = 0; // declare $count
foreach($cars as $keys){
if($keys[2]=='t')
$count=1;
}
foreach($cars as $key=>$keys){
if($count==1)
$cars[$key][2] = 't'; // change value to t like this
}
output:
Array
(
[0] => Array
(
[0] => 1
[1] => 1
[2] => t
)
[1] => Array
(
[0] => 2
[1] => 2
[2] => t
)
[2] => Array
(
[0] => 3
[1] => 3
[2] => t
)
[3] => Array
(
[0] => 4
[1] => 4
[2] => t
)
)
You were almost close, Just make this change, use reference symbol & to actual change
from
foreach($cars as $keys){
to
foreach($cars as &$keys){
Check this : https://eval.in/609879
$exists= false;
foreach($cars as $car)
{
if($car[2] == 't')
{
$exists= true;
}
}
if($exists)
{
for($i=0; $i<count($cars); $i++)
{
$cars[$i][2] = 't';
}
}
Here's the solution for you
<?php
$cars = array(
array(1,1,'f'),
array(2,2,'f'),
array(3,3,'t'),
array(4,4,'f')
);
if(in_array('t', array_column($cars, 2))){
$cars = array_map(function($v){
$v[2] = 't';
return $v;
}, $cars);
}

how to match some elements in associative array in php

I have a following array
Array
(
[0] => Array
(
[0] =>
)
[1] => Array
(
[0] => flatrate
[1] => flatrate3
[2] => freeshipping
)
[2] => Array
(
[0] => flatrate
[1] => flatrate2
[2] => flatrate3
[3] => flatrate4
[4] => freeshipping
)
)
Now, i need to match some element in this like
if freeshipping in above array . it should echo yes else no.
Please suggest, how can i do this.
for($i = 0; count($array); $i++){
if(in_array($string, $array[$i]) echo true;
}
you can do simple code like that :
foreach ($array as $key) {
foreach ($key as $value) {
if($value == "your condition")
{
echo 'yes';
}else{
echo 'no';
}
}
}
try it.
Create A function
function checkfreeShipping($arrData)
{
foreach($arrData as $data){
if(in_array('freeshipping',$data))
return true;
}
}
Call defined function to check Shipping -
if(checkfreeShipping($cartArr)){
echo "free Shipping";
}
else{
echo "Paid Shipping";
}

Associative index array to associative associative array

Problem
I have an array which is returned from PHPExcel via the following
<?php
require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php';
$excelFile = "excel/1240.xlsx";
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load($excelFile);
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$arrayData[$worksheet->getTitle()] = $worksheet->toArray();
}
print_r($arrayData);
?>
This returns:
Array
(
[Films] => Array
(
[0] => Array
(
[0] => Name
[1] => Rating
)
[1] => Array
(
[0] => Shawshank Redemption
[1] => 39
)
[2] => Array
(
[0] => A Clockwork Orange
[1] => 39
)
)
[Games] => Array
(
[0] => Array
(
[0] => Name
[1] => Rating
)
[1] => Array
(
[0] => F.E.A.R
[1] => 4
)
[2] => Array
(
[0] => World of Warcraft
[1] => 6
)
)
)
What I would like to have is
Array
(
[Films] => Array
(
[0] => Array
(
[Name] => Shawshank Redemption
[Rating] => 39
)
[1] => Array
(
[Name] => A Clockwork Orange
[Rating] => 39
)
)
[Games] => Array
(
[0] => Array
(
[Name] => F.E.A.R
[Rating] => 4
)
[1] => Array
(
[Name] => World of Warcraft
[Rating] => 6
)
)
)
The arrays names (Films, Games) are taken from the sheet name so the amount can be variable. The first sub-array will always contain the key names e.g. Films[0] and Games[0] and the amount of these can be varible. I (think I) know I will need to do something like below but I'm at a loss.
foreach ($arrayData as $value) {
foreach ($value as $rowKey => $rowValue) {
for ($i=0; $i <count($value) ; $i++) {
# code to add NAME[n] as keys
}
}
}
I have searched extensively here and else where if it is a duplicate I will remove it.
Thanks for any input
Try
$result= array();
foreach($arr as $key=>$value){
$keys = array_slice($value,0,1);
$values = array_slice($value,1);
foreach($values as $val){
$result[$key][] = array_combine($keys[0],$val);
}
}
See demo here
You may use nested array_map calls. Somehow like this:
$result = array_map(
function ($subarr) {
$names = array_shift($subarr);
return array_map(
function ($el) use ($names) {
return array_combine($names, $el);
},
$subarr
);
},
$array
);
Demo
Something like this should work:
$newArray = array();
foreach ($arrayData as $section => $list) {
$newArray[$section] = array();
$count = count($list);
for ($x = 1; $x < $count; $x++) {
$newArray[$section][] = array_combine($list[0], $list[$x]);
}
}
unset($arrayData, $section, $x);
Demo: http://ideone.com/ZmnFMM
Probably a little late answer, but it looks more like your tried solution
//Films,Games // Row Data
foreach ($arrayData as $type => $value)
{
$key1 = $value[0][0]; // Get the Name Key
$key2 = $value[0][1]; // Get the Rating Key
$count = count($value) - 1;
for ($i = 0; $i < $count; $i++)
{
/* Get the values from the i+1 row and put it in the ith row, with a set key */
$arrayData[$type][$i] = array(
$key1 => $value[$i + 1][0],
$key2 => $value[$i + 1][1],
);
}
unset($arrayData[$type][$count]); // Unset the last row since this will be repeated data
}
I think this will do:
foreach($arrayData as $key => $array){
for($i=0; $i<count($array[0]); $i++){
$indexes[$i]=$array[0][$i];
}
for($i=1; $i<count($array); $i++){
for($j=0; $j<count($array[$i]); $j++){
$temp_array[$indexes[$j]]=$array[$i][$j];
}
$new_array[$key][]=$temp_array;
}
}
print_r($new_array);
EDIT: tested and updated the code, works...

Calculating average value for array with PHP?

My head is exploding with this. I can't seem to create a working solution.
I have a file in this format:
99895|35378|0.01
99895|813|-0.97
99895|771|0.29
442|833|-1.06
442|485|-0.61
442|367|-0.14
442|478|0.77
442|947|-0.07
7977|987|0.76
7977|819|0.37
7977|819|0.36
7977|653|1.16
7977|1653|1.15
I want to calculate average values from third column for each id from the first column.
This seems so easy but I can't get this to work. How do you get averages for any said id from first column?
EDIT:
Some sample code I've written before:
$file = file_get_contents("results.txt");
$file = explode("
", $file);
$howMany = count($file);
for($a = 0;$a<$howMany;$a++)
{
$row = explode("|", $file[$a]);
$id = $row[0];
$howManyAlready = count($bigTable[$id]);
$bigTable[$id][$howManyAlready] = $row[2];
}
I've added the code. So far it gets the results into an array ( with offset corresponding to its id ) But I am having trouble with how to get those results and calculate average for each id and then present it on the screen.
Something like this should definitely work..
<?php
$arr=array();
$arrv=array_filter(file('myfile.txt'),'strlen');
foreach($arrv as $v)
{
array_push($arr,#array_pop(explode('|',$v)));
}
echo $avg = array_sum($arr)/count($arr);
You can try doing this :
$file = file_get_contents("results.txt");
$file = explode("
", $file);
$valuesPerID = Array();
foreach($file as $row)
{
$row_array = explode("|", $row);
$id = $row_array[0];
if(!array_key_exists($id, $valuesPerID))
{
$valuesPerID[$id] = Array();
}
$valuesPerID[$id][] = $row_array[2];
}
Now in the $valuesPerID array, you'll have all your ID as keys, and for each ID, all the values associated with the said ID. They you can easily calculate the average of these values !
You can use array mapping to assign value and id.
For example (assume that you have handled the text):
<?php
$data = array("99895|35378|0.01",
"99895|813|-0.97",
"99895|771|0.29",
"442|833|-1.06",
"442|485|-0.61",
"442|367|-0.14",
"442|478|0.77",
"442|947|-0.07",
"7977|987|0.76",
"7977|819|0.37",
"7977|819|0.36",
"7977|653|1.16",
"7977|1653|1.15");
$bucket = array();
$count = array();
foreach($data as $line) {
list($id, $what_s_this, $number) = explode("|", $line);
$count[$id]++;
$bucket[$id]+= (float)$number;
}
foreach($bucket as $id => $sum) {
echo "id:". $id. ", average". $sum / $count[$id]. "\n";
}
This should put you on the right track.
<?php
$values = array();
foreach (file('file.txt') as $line) {
list($id, $thingymabob, $value) = explode('|', $line);
if ( ! array_key_exists($id, $values)) {
$values[ $id ] = array();
}
array_push($values[ $id ], $value);
}
foreach ($values as $id => $value) {
printf(
"%d has an average of %f\n",
$id,
array_sum($value) / count($value)
);
}
Here some something I've just written.
In my example it takes it from a string.
<?php
$test1 = "";
$test2 = "";
$count1 = 0;
$count2 = 0;
$string = "99895|35378|0.01
99895|813|-0.97
99895|771|0.29
442|833|-1.06
442|485|-0.61
442|367|-0.14
442|478|0.77
442|947|-0.07
7977|987|0.76
7977|819|0.37
7977|819|0.36
7977|653|1.16
7977|1653|1.15";
$d = explode("\n", $string);
foreach ($d as $k => $v)
{
$d2 = explode("|", $v);
if ($d2[0] == '99895'){
$count1++;
$test1 += $d2[2];
}
if ($d2[0] == '442'){
$count2++;
$test2 += $d2[2];
}
}
$result1 = $test1 / $count1;
$result2 = $test2 / $count2;
echo $result1. " <br> ". $result2;
I don't know how well this will work as I don't know if the values are set or not.
If You try below code
<?php
$file_content = array();
$handle = fopen("test.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
// process the line read.
$line_ex = explode("|",$line);
array_push($file_content,$line_ex);
}
} else {
// error opening the file.
}
echo "<pre>";
print_r($file_content);
echo "<pre>";
?>
then You will get below output
Array
(
[0] => Array
(
[0] => 99895
[1] => 35378
[2] => 0.01
)
[1] => Array
(
[0] => 99895
[1] => 813
[2] => -0.97
)
[2] => Array
(
[0] => 99895
[1] => 771
[2] => 0.29
)
[3] => Array
(
[0] => 442
[1] => 833
[2] => -1.06
)
[4] => Array
(
[0] => 442
[1] => 485
[2] => -0.61
)
[5] => Array
(
[0] => 442
[1] => 367
[2] => -0.14
)
[6] => Array
(
[0] => 442
[1] => 478
[2] => 0.77
)
[7] => Array
(
[0] => 442
[1] => 947
[2] => -0.07
)
[8] => Array
(
[0] => 7977
[1] => 987
[2] => 0.76
)
[9] => Array
(
[0] => 7977
[1] => 819
[2] => 0.37
)
[10] => Array
(
[0] => 7977
[1] => 819
[2] => 0.36
)
[11] => Array
(
[0] => 7977
[1] => 653
[2] => 1.16
)
[12] => Array
(
[0] => 7977
[1] => 1653
[2] => 1.15
)
)
For determining average value from third column of corresponding first column - I am researching on it. When I will be done I'll put it here.
Try this:
$filename = 'results.txt';
$result = $counter = $values = array();
$file = fopen($filename, 'r') or die("Couldn't open $filename");
while ($line = fgets($file)) {
$content = explode('|', $line);
if (empty($content[0]) or empty($content[2]))
continue;
$values[$content[0]][] = (float) $content[2];
++$counter[$content[0]];
}
foreach ($values as $key => $value) {
$result[$key] = array_sum($value) / $counter[$key];
}
fclose($file);

count of duplicate elements in an array in php

Hi,
How can we find the count of duplicate elements in a multidimensional array ?
I have an array like this
Array
(
[0] => Array
(
[lid] => 192
[lname] => sdsss
)
[1] => Array
(
[lid] => 202
[lname] => testing
)
[2] => Array
(
[lid] => 192
[lname] => sdsss
)
[3] => Array
(
[lid] => 202
[lname] => testing
)
)
How to find the count of each elements ?
i.e, count of entries with id 192,202 etc
You can adopt this trick; map each item of the array (which is an array itself) to its respective ['lid'] member and then use array_count_value() to do the counting for you.
array_count_values(array_map(function($item) {
return $item['lid'];
}, $arr);
Plus, it's a one-liner, thus adding to elite hacker status.
Update
Since 5.5 you can shorten it to:
array_count_values(array_column($arr, 'lid'));
foreach ($array as $value)
{
$numbers[$value[lid]]++;
}
foreach ($numbers as $key => $value)
{
echo 'numbers of '.$key.' equal '.$value.'<br/>';
}
Following code will count duplicate element of an array.Please review it and try this code
$arrayChars=array("green","red","yellow","green","red","yellow","green");
$arrLength=count($arrayChars);
$elementCount=array();
for($i=0;$i<$arrLength-1;$i++)
{
$key=$arrayChars[$i];
if($elementCount[$key]>=1)
{
$elementCount[$key]++;
} else {
$elementCount[$key]=1;
}
}
echo "<pre>";
print_r($elementCount);
OUTPUT:
Array
(
[green] => 3
[red] => 2
[yellow] => 2
)
You can also view similar questions with array handling on following link
http://solvemyquest.com/count-duplicant-element-array-php-without-using-built-function/
The following code will get the counts for all of them - anything > 1 at the end will be repeated.
<?php
$lidCount = array();
$lnameCount = array();
foreach ($yourArray as $arr) {
if (isset($lidCount[$arr['lid']])) {
$lidCount[$arr['lid']]++;
} else {
$lidCount[$arr['lid']] = 1;
}
if (isset($lnameCount [$arr['lname']])) {
$lnameCount [$arr['lname']]++;
} else {
$lnameCount [$arr['lname']] = 1;
}
}
$array = array('192', '202', '192', '202');
print_r(array_count_values($array));
$orders = array(
array(
'lid' => '',
'lname' => '',
))....
$foundIds = array();
foreach ( $orders as $index => $order )
{
if ( isset( $foundIds[$order['lid']] ) )
{
$orders[$index]['is_dupe'] = true;
$orders[$foundIds[$order['lid']]]['is_dupe'] = true;
} else {
$orders[$index]['is_dupe'] = false;
}
$foundIds[$order['lid']] = $index;
}
Try this code :
$array_count = array();
foreach ($array as $arr) :
if (in_array($arr, $array_count)) {
foreach ($array_count as $key => $count) :
if ($key == $arr) {
$array_count[$key]++;
break;
}
endforeach;
} else {
$array_count[$arr] = 1;
}
endforeach;
Check with in_array() function.

Categories