Last letters remove form array in foreach loop - php

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);
}

Related

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 greatest value from json array in 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
)

Remove number from array with repeated digits

I want to remove the numbers from array which have repeated digits in them.
array('4149','8397','9652','4378','3199','7999','8431','5349','7068');
to
array('8397','9652','4378','8431','5349','7068');
I have tried this thing
foreach($array as $key => $value) {
$data = str_split($value, 1);
$check = 0;
foreach($data as $row => $element) {
$check = substr_count($value, $element);
if($check != 1) {
array_diff($array, array($value));
}
}
}
You can filter the array using a regular expression that matches:
(.) any character
.* followed by zero or more characters
\1 followed by the first character one more time
Example code:
$array = array('4149','8397','9652','4378','3199','7999','8431','5349','7068');
$result = array_filter(
$array,
function ($number) {
return !preg_match('/(.).*\\1/', $number);
}
);
echo implode(', ', $result), PHP_EOL;
Output:
8397, 9652, 4378, 8431, 5349, 7068
This should work for you:
Here I first str_split() each element into a separate array with array_map(). After this I just compare the splitted array with the same array just with array_unique() digits and check if they are the same. If yes I return the implode() number otherwise false. And at the end I just filter the elements with false with array_filter() out.
So in other words I just compare these 2 arrays with they are the same:
array1:
Array
(
[0] => Array
(
[0] => 4
[1] => 1
[2] => 4
[3] => 9
)
//...
)
array2:
Array
(
[0] => Array
(
[0] => 4
[1] => 1
[3] => 9
)
//...
)
Code:
<?php
$arr = ['4149', '8397', '9652', '4378', '3199', '7999', '8431', '5349', '7068'];
$arr = array_map("str_split", $arr);
$result = array_filter(array_map(function($v1, $v2){
return ($v1 === $v2?implode("", $v1):false);
}, $arr, array_map("array_unique", $arr)));
print_r($result);
?>
output:
Array ( [1] => 8397 [2] => 9652 [3] => 4378 [6] => 8431 [7] => 5349 [8] => 7068 )

Remove unset array containing specific string

I have the following array imported from a CSV:
Array
(
[0] => Array
(
[0] => QUARTERLY STATS;Q1/2011;Q2/2011;Q3/2011;Q4/2011;Q1/2012;Q2/2012;Q3/2012;Q4/2012;Q1/2013;Q2/2013;Q3/2013;Q4/2013;Q1/2014
)
[1] => Array
(
[0] => January;7500;8800;9500;10000;10500;11000;11500;12000;12500;13000;13420;13820;14200
)
[2] => Array
(
[0] => ;;17
[1] => 30%;8%;5
[2] => 30%;5%;4
[3] => 80%;4
[4] => 50%;4
[5] => 30%;4
[6] => 20%;4%;3
[7] => 20%;3%;2
[8] => 70%
)
[3] => Array
(
[0] => TOTAL;7500;8500;9500;11000;12500;11400;11800;13000;12500;13000;13420;13820;14200
)
[4] => Array
(
[0] => ;;17
[1] => 30%;7
[2] => 95%;5
[3] => 26%;5%;4
[4] => 76%;4
[5] => 55%;4
[6] => 35%;4
[7] => 17%;4%;3
[8] => 23%;2
[9] => 98%;2
[10] => 75%
)
So,
I would like to get rid of all arrays containing "% and TOTAL".
I thought to loop through and unset the matching case:
$remove ="TOTAL";
foreach ($csv as $key => $value){
if (in_array($remove,$value[$key])){
unset($value[$key]);
}
}
This is the error I got:
Warning: in_array() expects parameter 2 to be array, null given
My PHP Version 5.3.10
Would you do it that way or would you use the array_filter?
I am browsing since 2 hours the forum but I could not find any hint helping me out.
Cheers.
You can try by preg_replace for removing TOTAL & %. If you want to remove the element from array then use unset & finally use array_filter for removing null elements.
$newArr = array();
foreach($arr as $key=>$value){
foreach($value as $k=>$v){
$newArr[$key][$k] = preg_replace('/(TOTAL)|(%)/', '', $v); //for removing TOTAL & %
unset($arr[$key][$k]); //for unset the array elements that contains TOTAL & %
}
}
//Output by replacement
print '<pre>';
print_r($newArr);
print '</pre>';
//output after using unset
print '<pre>';
print_r(array_filter($arr));
print '</pre>';
In your case:
foreach ($csv as $subArray)
{
for ($i = 0, $len = count($subArray); $i < $len; $i++)
{
if (strpos($subArray[$i], $remove) !== false)
unset($subArray[$i])
}
}
Comments:
strict comparasion for strpos, if we use !=, then 0 position would be equals to false.
inner loop is "for-loop" bevause it's better to avoid changing content of array inside foreach.
$arr[][] = ("QUARTERLY STATS;Q1/2011;Q2/2011;Q3/2011;Q4/2011;Q1/2012;Q2/2012;Q3/2012;Q4/2012;Q1/2013;Q2/2013;Q3/2013;Q4/2013;Q1/2014");
$arr[][] = ("January;7500;8800;9500;10000;10500;11000;11500;12000;12500;13000;13420;13820;14200");
$arr[] = array(";;17","30%;8%;5","30%;5%;4","80%;4","50%;4","30%;4","20%;4%;3","20%;3%;2","70%");
$arr[][] = ("TOTAL;7500;8500;9500;11000;12500;11400;11800;13000;12500;13000;13420;13820;14200");
$arr[] = array("30%;7","95%;5","26%;5%;4","76%;4","55%;4","35%;4","17%;4%;3","23%;2","98%;2","75%");
$newArr = array();
foreach($arr as $key=>$value) {
foreach($value as $k=>$v) {
$newArr[$key][$k] = preg_replace('/(TOTAL)|(%)/', '', $v); //for removing TOTAL & %
unset($arr[$key][$k]); //for unset the array elements that contains TOTAL & %
}
unset($arr[$key]); // IT does not unset ARR[2] ARR[3] and ARR[4] containing TOTAL & %
}
Output by replacement
print '<pre>';
print_r($newArr);
print '</pre>';
Output after using unset
print '<pre>';
print_r(array_filter($arr));
print '</pre>';
I did create exactly the same ARRAY as imported from CSV.
unset does not unset ARRAY2,3,4 which is containing TOTAL AND %.
unset does not unset ARRAY2,3,4 which is containing TOTAL AND %.

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