Find greatest value from json array in php - php

I'm using the following code to display the time for each character from a JSON. But the problem is there are repeated elements. I only want to select the highest value for each.
For example, highest value of s is 85, t is 84.
I tried the max() function, but only returning largest of all:
<?php
$speedArray = json_decode('[{"key":"e","time":35},{"key":"s","time":43},{"key":"t","time":39},{"key":"t","time":84},{"key":"s","time":85},{"key":"s","time":27},{"key":"t","time":80}]', true);
foreach ($speedArray as $timing) {
echo $timing['key'].$timing['time']."<br/>";
}
?>

First I would create a $key mapping and put all the values as array:
<?php
$speedArray = json_decode('[{"key":"e","time":35},{"key":"s","time":43},{"key":"t","time":39},{"key":"t","time":84},{"key":"s","time":85},{"key":"s","time":27},{"key":"t","time":80}]', true);
$keys = array();
foreach ($speedArray as $key) {
$keys[$key["key"]][] = $key["time"];
}
print_r($keys);
The output would be:
Array
(
[e] => Array
(
[0] => 35
)
[s] => Array
(
[0] => 43
[1] => 85
[2] => 27
)
[t] => Array
(
[0] => 39
[1] => 84
[2] => 80
)
)
Now it is easier to get the greatest of it. Using the max() function:
<?php
$speedArray = json_decode('[{"key":"e","time":35},{"key":"s","time":43},{"key":"t","time":39},{"key":"t","time":84},{"key":"s","time":85},{"key":"s","time":27},{"key":"t","time":80}]', true);
$keys = array();
foreach ($speedArray as $key) {
$keys[$key["key"]][] = $key["time"];
}
foreach ($keys as $key => $vals) {
echo "{$key}: " . max($vals) . "\n";
}
I get to this output:
e: 35
s: 85
t: 84
Demo: http://ideone.com/g4zULB

Getting max values for each key with a single loop and max function:
$speedArray = json_decode('[{"key":"e","time":35},{"key":"s","time":43},{"key":"t","time":39},{"key":"t","time":84},{"key":"s","time":85},{"key":"s","time":27},{"key":"t","time":80}]', true);
$result = [];
foreach ($speedArray as $v) {
(isset($result[$v['key']]))?
$result[$v['key']] = max($result[$v['key']], $v['time'])
: $result[$v['key']] = $v['time'];
}
print_r($result);
THe output:
Array
(
[e] => 35
[s] => 85
[t] => 84
)

Related

move a specific subarray to the top of a multidimensional array

I have an array of rows (from a mysql table)
And need to move to the top a subarray - i.e. a row - having id = $x
Tried a modified solution from here - without success
$st = $db->prepare("select id, nick from presto where id < 4");
$st->execute();
$rows = $st->fetchAll(PDO::FETCH_ASSOC);
print_r($rows);
result
Array ( [0] => Array ( [id] => 52 [nick] => 5fb63a1a8bcbf ) [1] => Array ( [id] => 54 [nick] => 5fb63a1a75171 ) [2] => Array ( [id] => 59 [nick] => 5fb63a1a91e68 ) )
$x = 54;
foreach($rows as $key => $val){
if($key['id'] == $x){ // line 155
unset($rows[$key]);
array_unshift($rows, $val);
}
}
and getting Warning - Trying to access array offset on value of type int on line 155
please help
$key on line 155 is the index/iteration/position in the array/foreach, which is an integer, not an array. $val is your data array from each iteration.
Try this.
$x = 54;
foreach($rows as $key => $val){
if($val['id'] === $x){ // line 155
unset($rows[$key]);
array_unshift($rows, $val);
}
}

Last letters remove form array in foreach loop

I want to remove the last few letters from an array in a for-each loop. I am trying to show bl_date without /2018. Now its showing 07/10/2018 & 06/30/2018. How can echo like this 07/10 & 06/30?
Array
Array
(
[0] => stdClass Object
(
[id] => 18
[bl_user] => 61
[bl_date] => 07/10/2018
)
[1] => stdClass Object
(
[id] => 17
[bl_user] => 61
[bl_date] => 06/30/2018
)
)
PHP
$resultstr = array();
foreach ($billings as $billing) {
$resultstr[] = $billing->bl_date;
}
echo implode(" & ",$resultstr);
One option is to use substr() to remove the last 5 characters of the string
Like:
$resultstr = array();
foreach ($billings as $billing) {
$resultstr[] = substr( $billing->bl_date, 0, -5 );
}
echo implode(" & ",$resultstr);
This will result to:
07/10 & 06/30
Doc: substr()
You need to use substr function:
foreach ($billings as $billing) {
$resultstr[] = substr($billing->bl_date, 0, 5);
}

How to transfer one array to another array in php

I have a simple Two array
$ages[] = array("Peter"=>22, "Clark"=>32, "John"=>28);
$ages1[] = array("demo"=>22);
When I print this arrays it should be like following:
Array
(
[0] => Array
(
[Peter] => 22
[Clark] => 32
[John] => 28
)
)
Array
(
[0] => Array
(
[demo] => 22
)
)
But I want to create third array which will be show demo kye value into first array like following:
Array
(
[0] => Array
(
[Peter] => 22
[Clark] => 32
[John] => 28
[demo] => 22
)
)
Can we do two array into single array in PHP like Above
Not sure what are you trying to achieve here...little more context would be helpful. But this is how you can do this,
$ages[] = array("Peter"=>22, "Clark"=>32, "John"=>28);
$ages1[] = array("demo"=>22);
$result[] = array_merge($ages[0],$ages1[0]);
This would do the job.
<?php
$ages[] = array("Peter"=>22, "Clark"=>32, "John"=>28);
$ages1[] = array("demo"=>22);
$output = prepend_array($ages,$ages1);
print_r($output);
// Function to prepend arrays
function prepend_array()
{
$num_args = count(func_get_args());
$new_array = array();
foreach (func_get_args() as $params){
foreach($params as $out_key => $param)
{
foreach($param as $key => $value)
$new_array[$out_key][$key] = $value;
}
}
return $new_array;
}

Remove parent array from multidimensional array in php

using php how to get array result into below way,
Array
(
[3] => Array
(
[15] => 15
[16] => 16
[17] => 17
[18] => 18
[19] => 19
)
)
how to convert above array into below format,
Array
(
[0] => 15
[1] => 16
[2] => 17
[3] => 18
[4] => 19
)
array_values() is your friend;
Presuming your array exists in a variable called $array;
$newArray = array_values($array[3]);
you should use RecursiveArrayIterator to remove parent array
$arr = new RecursiveIteratorIterator(new RecursiveArrayIterator($multidimensional_array));
$new_arr = iterator_to_array($arr, false);
try this, if you have more than one sub-array, it will work.
$arr = array(3 =>
array
(
15 => 15,
16 => 16,
17 => 17,
18 => 18,
19 => 19
)
);
$new = array();
foreach ($arr as $v){
$new = array_merge($new , array_values($v)) ;
}
echo "<pre>"; print_r($new);
Working Demo
Have not tested it but should work as per your requirement.
<?php
$parent array = array(); // The array which you want to change
$result_array = array(); // The array that will hold the results
foreach( $parent_array as $child_array )
{
if( is_array( $child_array ) )
{
foreach( $child_array as $element )
{
$result_array[] = $element
}
}
}
echo '<pre>';
print_r($result_array);
echo '</pre>';
?>
it's pretty simple, as you can just assign the array holding variable to the values of one index …
<?php
/* build list */
for($i=15;$i<=19;$i++)
$b[$i] = $i;
$a[3] = $b;
var_export($a);
/* make array smaller again */
$a = $a[3];
var_export($a);
/* reindexing, just values */
$a = array_values( $a );
var_export($a);
?>
the reindexing part is done by a build-in function, also have a look on php.net for the linked functions for arrays, you can do massive stuff simple with them.

Find in array and get count of each string

I am fetching some data from the db and then push them to an array. I need to find the count of some strings and print out the result (count) in an efficient way:
Array
(
[0] => q1-1,q2-2,q3-2,q4-1,q5-2,q6-3,q7-1,q8-4,
[1] => q1-1,q2-2,q3-1,q4-3,q5-3,q6-3,q7-2,q8-1,
[2] => q1-1,q2-1,q3-1,q4-1,q5-1,q6-2,q7-2,q8-2,
[3] => q1-3,q2-1,q3-1,q4-1,q5-2,q6-3,q7-1,q8-1,
[4] => q1-2,q2-2,q3-3,q4-1,q5-3,q6-3,q7-1,q8-1,
[5] => q1-1,q2-2,q3-3,q4-1,q5-2,q6-3,q7-1,q8-1,
[6] => q1-3,q2-1,q3-1,q4-3,q5-2,q6-3,q7-2,q8-4,
[7] => q1-2,q2-2,q3-3,q4-1,q5-2,q6-5,q7-1,q8-1,
[8] => q1-1,q2-1,q3-2,q4-3,q5-3,q6-5,q7-1,q8-1,
[9] => q1-2,q2-1,q3-1,q4-1,q5-3,q6-3,q7-1,q8-1,
[10] => q1-3,q2-2,q3-3,q4-3,q5-4,q6-3,q7-1,q8-1,
...
)
Sample data is above.
I need to know how many occurences of q1-1, q1-2 ... q8-4 is in the array and print out readable version. Ex. The are 23: q1-1, 412: q1-2 and so on.
I was going to create an array of each string that needs to be searched that iterate through the array. For every result increment the resultVariable for that string but I'm not sure if that's the best way.
Suggestions?
Pretty simple, loop on your array, create sub arrays, and create a counter array:
$counts = array () ;
foreach ( $your_array as $row ) {
$sub = explode(',', $row);
foreach ( $sub as $subval ) {
if ( array_key_exists ( $subval, $counts ) ) {
$counts[$subval] ++ ;
} else {
$counts[$subval] = 1 ;
}
}
}
Here is $counts:
Array (
'q1-1' => 23,
'q1-2' => 9,
// and so on....
);
Try:
$arr = array(...); //your array
$count = array();
foreach($arr as $v) {
$substr = explode(',', $v);
foreach($substr as $m) {
if(strstr($v, $m) !== FALSE)
$count[$m]++;
}
}
Printing the counts,
foreach($count as $k => $v)
echo "Count for '$k': ". $v;

Categories