PHP Array count and get element values - php

I'm pretty new to PHP and programming so I'm having troubles with this thing.
The purpose of the whole situation is to read a column from tab delimited file (already did that), get all different items in it, count them individually and put them in table with Column1[item value - label], Column2[count].
I have the whole column in 1 dimension array. Now, I want to list all the items there and their counts beside. The problem is, I could have more than 10 different items, even more, so I can't do it manually (name 10 variables and count each) like this:
$arr = array("complete","fail","complete","exit","fail","fail","complete");
function isComplete($value){
return ($value == "complete") ? true : false;
}
$complete = array_filter($array, 'isComplete');
<tr>
<td>Complete</td>
<td><?php echo count($complete)?></td>
</tr>
-- > Complete = 3
I want to avoid manually creating every function for each value because values can differ from file to file.
The number of items in $array can go up to 20+k so I need all automated. Can someone help me with this?

How about going through the array and placing the counts in another array? ($arrCount)
$arr = array("complete","fail","complete","exit","fail","fail","complete");
$arrCount = Array();
foreach($arr as $value){
$arrCount[$value] = array_key_exists($value,$arrCount) ? $arrCount[$value]+1 : 1;
//If this key exists, add 1 to it, else make it equal to 1
}
This would create an array with the keys being the various labels and the value equally to the label total.
print_r output:
Array ( [complete] => 3 [fail] => 3 [exit] => 1 )

Psuedo code:
$arr = array("complete","fail","complete","exit","fail","fail","complete");
$counts = array();
foreach($arr => $key as $value)
{
if(array_key_exists($value, $counts))
{
$counts[$value]++;
}else{
$counts[$value] = 1;
}
}
foreach($counts => $key as $value)
{
echo '<tr>
<td>' . $key . '</td>
<td>' . $value . '</td>
</tr>';
}
We are making arrays of the elements in the list. If the item exists, increase otherwise create with value 1. Than loop another time to show to the user the total count of each item.

Maybe I'm missing the point, but what is the problem with a normal loop?
For example:
function countByValue($array, $value){
$count = 0;
foreach($array as $val){
if ($val == $value){
$count++;
}
}
return $count;
}
And call it with
$complete = countByValue($arr, 'complete');
If you want to count them all at once go with F4r-20 answer.

Related

PHP Array Values same element in different formats and posting from div data

I have a foreach loop for an array
foreach ($somethings as $key2 => $something)
{
$value = 0;
if ($something['ElementID'] == $value)
{
unset($available);
}
$total += $something['Cost'];
$singleprice = $available['Cost'];
}
I need to be able to return $total and $singleprice - Total adding up all the values within the key, $singleprice returning only 1 instead of all added up
The only way I've managed to return this value is by creating another foreach loop within this foreach loop like so:
foreach ($somethings as $key2 => $something)
{
$value = 0;
if ($something['ElementID'] == $value)
{
unset($available);
}
foreach($somethings as $key3 => $singlesomething)
{
$singleprice = $singlesomething['Cost'];
}
$total += $something['Cost'];
}
Why will the above first method return nothing? I then use this variable which now has the data in a Div Data- (data-single-cost="'.$singleprice.'" ) which is then used to POST a form
$singleprice = $_POST['single-cost'];
Yet it returns 0 even with the second method successfully getting the value
any ideas what I'm doing wrong?
I guess its because somehow program goes into the if and you have unset available in it, so singleprice gots nothing.
Maybe you should get a Xdebug and try some step debug to see what happend.

PHP dynamic array name with loop

I need to get values of array through a loop with dynamic vars.
I can't understand why the "echo" doesn’t display any result for "$TAB['b']".
Do you know why ?
The test with error message : https://3v4l.org/Fp3GT
$TAB_a = "aaaaa";
$TAB['b'] = "bbbbb";
$TAB['b']['c'] = "ccccc";
$TAB_paths = ["_a", "['b']", "['b']['c']"];
foreach ($TAB_paths as $key => $value) {
echo "\n\n\${'TAB'.$value} : "; print_r(${'TAB'.$value});
}
You are treating the array access characters as if they are part of the variable name. They are not.
So if you have an array $TAB = array('b' => 'something');, the variable name is $TAB. When you do ${'TAB'.$value}, you're looking for a variable that's actually named $TAB['b'], which you don't have.
Since you say that you just want to be able to access array indexes dynamically based on the values in another array, you just put the indexes alone (without the array access characters) in the other array.
$TAB['b'] = 'bbbbbb';
$TAB['c'] = 'cccccc';
$TAB_paths = array('b', 'c');
foreach ($TAB_paths as $key => $value) {
echo "\n\n".'$TAB['."'$value'".'] : ' . $TAB[$value];
}
Output:
$TAB['b'] : bbbbbb
$TAB['c'] : cccccc
DEMO
It's unclear what you're trying to do, although you need to include $TAB_all in $TAB_paths:
$TAB_paths = [$TAB_all['a'], $TAB_all['aside']['nav']];
Result:
${TAB_all.aaaaa} : ${TAB_all.bbbbb} :
Not certain what you're needing. My guess you need to merge two arrays into one. Easiest solution is to use the array_merge function.
$TAB_paths = array_merge($TAB_a1, $TAB_a2);
You can define the variable first
foreach ($TAB_all as $key => $value) {
${"TAB_all" . $key} = $value;
}
Now Explore the result:
foreach ($TAB_all as $key => $value) {
print_r(${"TAB_all" . $key});
}

Get First And Last Data From conditioned foreach loop

Hello here i am with freaky problem,i wants the first data and last data from for-each loop. for that i have seen this answer. this would be really helpful but here my condition is really a little bit complex.
I have loop as following
<?php
$count = 0;
$length = count($myDataArray);
foreach ($myDataArray as $value) {
if($count >= 7)
{
//Some Data to Print
//this is first data for me
<tr >
<td><?=$myfinaldate?></td>
<td><?=$stockdata[1]?></td>
<td><?=$stockdata[2]?></td>
<td><?=$stockdata[3]?></td>
<td <?php if($count == 8)echo "style='background-color:#47ff77;'"; ?>><?=$stockdata[4]?></td>
<td><?=$stockdata[5]?></td>
<td><?php echo $mydate; ?></td>
</tr>
<?php
}
$count++;
}
Now How can i Get First And Last Data from loop ?
I imagine you could use your length attribute.
As you have the total of your array, just check
myDataArray[0] and myDataArray[$length-1] ?
To fetch first and last value of the array use the below function :
$array = $myDataArray;
$array_values = array_values($myDataArray);
// get the first value in the array
print $array_values[0]; // prints 'first item'
// get the last value in the array
print $array_values[count($array_values) - 1]; // prints 'last item'
You can use array_values to remove the keys of an array and replace them with indices. If you do this, you can access the specified fields directly. Like this you can check for your requirements on the array without looping over it, as shown in the if-conditions below:
$length = count($myDataArray);
$dataArrayValues = array_values($myDataArray);
$wantedFields = [];
if ($length >= 8) {
$wantedFields[] = $dataArrayValues[7];
if ($length > 8) {
$wantedFields[] = end($dataArrayValues);
}
}
Due to the conditions you will not print the 8th field twice in case it is the last field as well.
foreach ($wantedFields as $value) {
<tr>
... //Your previous code
</tr>
}

How to find Smallest value of 2 different Variables in JSON and subtract other elements with that values

I need to find the smallest value of 2 variables in JSON object of particular key and subtract all keys with that value. Kindly lookinto following JSON Data
$print = '{"Table":[
{"Column":2,"Length":1,"Number":"A4","Row":12,"zindex":0},
{"Column":2,"Length":1,"Number":"A3","Row":11,"zindex":0},
{"Column":2,"Length":1,"Number":"A2","Row":9,"zindex":1},
{"Column":2,"Length":1,"Number":"A1","Row":8,"zindex":1},
{"Column":3,"Length":1,"Number":"B4","Row":12,"zindex":0},
{"Column":3,"Length":1,"Number":"B3","Row":11,"zindex":0},
{"Column":3,"Length":1,"Number":"B2","Row":9,"zindex":0},
{"Column":3,"Length":1,"Number":"B1","Row":8,"zindex":0},
{"Column":4,"Length":1,"Number":"C4","Row":12,"zindex":0},
{"Column":4,"Length":1,"Number":"C3","Row":11,"zindex":0},
{"Column":4,"Length":1,"Number":"C2","Row":9,"zindex":0},
{"Column":4,"Length":1,"Number":"C1","Row":8,"zindex":0}],"ResponseStatus":200,"Message":null}';
I want above JSON Data as given below.
$print = '{"Table":[
{"Column":2,"Length":1,"Number":"A4","Row":1,"zindex":0},
{"Column":2,"Length":1,"Number":"A3","Row":0,"zindex":0},
{"Column":2,"Length":1,"Number":"A2","Row":1,"zindex":1},
{"Column":2,"Length":1,"Number":"A1","Row":0,"zindex":1},
{"Column":3,"Length":1,"Number":"B4","Row":1,"zindex":0},
{"Column":3,"Length":1,"Number":"B3","Row":0,"zindex":0},
{"Column":3,"Length":1,"Number":"B2","Row":1,"zindex":1},
{"Column":3,"Length":1,"Number":"B1","Row":0,"zindex":1},
{"Column":4,"Length":1,"Number":"C4","Row":1,"zindex":0},
{"Column":4,"Length":1,"Number":"C3","Row":0,"zindex":0},
{"Column":4,"Length":1,"Number":"C2","Row":1,"zindex":1},
{"Column":4,"Length":1,"Number":"C1","Row":0,,"zindex":1}],"ResponseStatus":200,"Message":null}';
In the above JSON data kindly look into Row and zindex.
zindex has two values "0 and 1", here I want php code to find smallest value of zindex 0 separately and subtract remaining values of zindex 0 alone and same with zindex 1.
I have a PHP code that finds minimum value of row and subtract remaining rows with that value. But I dont know how to do it separately for different zindexs.
$rows = array();
$print = json_decode($print, true); // decode
foreach($print['Table'] as $val) { $rows[] = $val['Row']; }
$least = min($rows); // get least // $least = min(array_column($print['Table'], 'Row'));
foreach($print['Table'] as &$val) {
$val['Row'] -= $least; // make subtractions
}
$print = json_encode($print); // re encode
Kindly help me to solve this problem in PHP.
Try to replace the first foreach by:
foreach($print['Table'] as $val) {
if (!isset($rows[$val['zindex']])) {
$rows[$val['zindex']] = array();
}
$rows[$val['zindex']][] = $val['Row'];
}
Instead of having a 1-dimensional array with values, the array is 2-dimensional, having all Row values for each value of zindex.
Then, $least should be an array as well:
$least = array();
foreach ($rows as $zindex = $row) {
$least[$zindex] = min($row);
}
That will calculate the minimum value for each value of zindex separately.
Finally, the last foreach should discriminate for zindex as well:
foreach ($print['Table'] as &$val) {
$val['Row'] -= $least[$val['zindex']];
}
Success!

shift array without indexOfOutBounds

I have 2 array's with the same length. array $gPositionStudents and array $gPositionInternships. Each student is assigned to a different internship, That part works.
Now I want the first element (index 0) of $gPositionStudent refer to the second (index 1) element of array $gPositionInternship. That implicitly means that the last element of $gPositionStudents refer to the first element of $gPositionInternship. (I included a picture of my explanation).
My Code is:
// Make table
$header = array();
$header[] = array('data' => 'UGentID');
$header[] = array('data' => 'Internships');
// this big array will contains all rows
// global variables.
global $gStartPositionStudents;
global $gStartPositionInternships;
//var_dump($gStartPositionInternships);
$rows = array();
$i = 0;
foreach($gStartPositionStudents as $value) {
foreach($gStartPositionInternships as $value2) {
// each loop will add a row here.
$row = array();
// build the row
$row[] = array('data' => $value[0]['value']);
//if($value[0] != 0 || $value[0] == 0) {
$row[] = array('data' => $gStartPositionInternships[$i]);
}
$i++;
// add the row to the "big row data (contains all rows)
$rows[] = array('data' => $row);
}
$output = theme('table', $header, $rows);
return $output;
Now I want that I can choose how many times, we can shift. 1 shift or 2 or more shifts. What I want exists in PHP?
Something like this:
//get the array keys for the interns and students...
$intern_keys = array_keys($gStartPositionInternships);
$student_keys = array_keys($gStartPositionStudents);
//drop the last intern key off the end and pin it to the front.
array_unshift($intern_keys, array_pop($intern_keys));
//create a mapping array to join the two arrays together.
$student_to_intern_mapping = array();
foreach($student_keys as $key=>$value) {
$student_to_intern_mapping[$value] = $intern_keys[$key];
}
You'll need to modify it to suit the rest of your code, but hopefully this will demonstrate a technique you could use. Note the key line here is the one which does array_unshift() with array_pop(). The comment in the code should explain what it's doing.
I think you want to do array_slice($gPositionsStudents, 0, X) where X is the number of moves to shift. This slices of a number of array elements. Then do array_merge($gPositionsStudents, $arrayOfSlicedOfPositions); to append these to the end of the original array.
Then you can do an array_combine to create one array with key=>value pairs from both arrays.

Categories