My string looks like:
244.53.66=1,53.646.77=1,666.534.23=5,664.521.64=3,535.777.54=2,533.886=5,22.153=5,643.786=2
I exploded it like:
$string = "244.53.66=1,53.646.77=1,666.534.23=5,664.521.64=3,535.777.54=2,533.886=5,22.153=5,643.786=2";
$array = explode(",", $string);
$array2=array();
for($i = 0; $i<count($array); $i++)
{
array_push($array2, explode("=",$array[$i]));
}
now $array2 got these values:
$array2[0][0] = "244.53.66";
$array2[0][1] = "1";
$array2[1][0] = "53.646.77";
$array2[1][1] = "1";
etc.
How Can I count all values each type, example:
2 x 1 (two records with value 1), 1x1(1 record with value 1) itd.
I want to store this as array:
$array3[index] = "amount same values";
Can You help me?
You need first to get the IDs in a seperate array, then use array_count_valuesto count the number of the IDs.
Here's the final code:
<?php
$string = "244.53.66=1,53.646.77=1,666.534.23=5,664.521.64=3,535.777.54=2,533.886=5,22.153=5,643.786=2";
$array = explode(",", $string);
$array2=array();
for($i = 0; $i<count($array); $i++)
{
array_push($array2, explode("=",$array[$i]));
}
$array3 = array();
//Iterate through array 2 to extract all IDs
for($i = 0; $i<count($array2); $i++)
{
array_push($array3, $array2[$i][1]);
}
$vals = array_count_values($array3);
print_r($vals);
?>
Which outputs
Array
(
[1] => 2
[5] => 3
[3] => 1
[2] => 2
)
Happy coding on StackOverflow !
Related
Given an array, I would like to display the count of distinct pairs of elements whose sum is equal to K -
I've written code as below, but I am unable to put array_diff to good use :\
<?PHP
function numberOfPairs($a, $k) {
$cnt = 0;
for($i=0; $i<count($a); $i++){
for($j=$i; $j<count($a); $j++){
if($a[$i]+$a[$j] == $k){
$arrRes[$i][0] = $a[$i];
$arrRes[$i][1] = $a[$j];
$cnt++;
}
}
}
sort($arrRes);
//print $cnt;
$d = $cnt;
for($i=0; $i<count($arrRes); $i++){
for($j=0; $j<count($arrRes); $j++){
$diff = array_diff($arrRes[$i], $arrRes[$j]);
if($diff == null)
$d += 1;
}
}
print $d;
}
$a = [6,6,3,9,3,5,1];
$k = 12;
numberOfPairs($a, $k);
?>
Here, the output arrays with sum equal to 12 are, i.e, the result of $arrRes is -
[0] => Array ( [0] => 3 [1] => 9 )
[1] => Array ( [0] => 6 [1] => 6 )
[2] => Array ( [0] => 6 [1] => 6 )
[3] => Array ( [0] => 9 [1] => 3 )
The count is 4, but the count should be 2, as (6,6) and (3,9) are the only distinct pairs.
You can simplify your solution, by using fact that arrays in php are hashmaps:
function numberOfPairs($a, $k) {
$used=[];
for ($i=0; $i<count($a); $i++)
for ($j=$i+1; $j<count($a); $j++) {
$v1 = min($a[$i], $a[$j]);
$v2 = max($a[$i], $a[$j]);
if ($k == $v1+$v2)
$used[$v1.'_'.$v2] = true;
}
return count($used);
}
$a = [6,6,3,9,3,5,1];
$k = 12;
echo numberOfPairs($a, $k);
You can create a flat array with used numbers and check so that you don't use them again with in_array.
function numberOfPairs($a, $k) {
$cnt = 0;
$used=[];
for($i=0; $i<count($a); $i++){
for($j=$i; $j<count($a); $j++){
if($a[$i]+$a[$j] == $k && !in_array($a[$i], $used) && !in_array($a[$i],$used)){
$arrRes[$i][0] = $a[$i];
$arrRes[$i][1] = $a[$j];
$used[] = $a[$i];
$used[] = $a[$j];
$used = array_unique($used);
$cnt++;
}
}
}
sort($arrRes);
//print $cnt;
// Not sure what the code below does, but I just left it the way it was.
$d = $cnt;
for($i=0; $i<count($arrRes); $i++){
for($j=0; $j<count($arrRes); $j++){
$diff = array_diff($arrRes[$i], $arrRes[$j]);
if($diff == null)
$d += 1;
}
}
print $d;
}
$a = [6,6,3,9,3,5,1];
$k = 12;
numberOfPairs($a, $k);
Try it here https://3v4l.org/lDe5V
Sort array and move indexes from both ends until they are not overlapped that gets O(n log n) instead of O(n^2) in accepted answer
function numberOfPairs($a, $k) {
sort($a);
$i = 0;
$j = count($a)-1;
// save last inseted array to avoid duplicates
$last = [];
while($i < $j) {
$s = $a[$i] + $a[$j];
if($s == $k) {
$t = [$a[$i++], $a[$j--]];
// Check for duplicate
if ($t != $last) {
$d[] = [$a[$i++], $a[$j--]];
$last = $t;
}
}
elseif($s > $k) $j--;
else $i++;
}
return $d;
}
demo
This is my method for finding distinct pairs of addends given an array and a target sum.
array_count_values() will reduce the input array size by condensing duplicate addends and storing them as keys (and their number of occurrences as values).
ksort() is called to ensure that the addends are processed in ascending order. This is crucial to avoid processing addends that are beyond the midpoint of the number set.
each iteration, store addends that are "less than or equal to" half of k AND have a matching addend.
when the addend multiplied by 2 is "greater than or equal to" k, do not continue to iterate.
Code: (Demo)
function numberOfPairs($a,$k){
$a=array_count_values($a); // enable use of the very fast isset() function and avoid iterating duplicates
ksort($a); // order so that only the lower values need to be iterated
foreach($a as $num=>$occur){
if(($double=$num*2)>=$k){ // we are at or past the middle
if($double==$k && $occur>1) $result[]=[$num,$k-$num]; // addends are equal and 2 exist, store before break
break;
}elseif(isset($a[$k-$num])){ // matching addend found, store & continue
$result[]=[$num,$k-$num];
}
}
var_export($result);
}
$a = [6,6,3,9,3,5,1];
$k = 12;
numberOfPairs($a,$k);
Output:
array (
0 =>
array (
0 => 3,
1 => 9,
),
1 =>
array (
0 => 6,
1 => 6,
),
)
array_count_values() is probably the most expensive function call in the snippet, but it sets up all subsequent processes to be fast, concise, direct, and logical (and I think, readable).
I have a php string formed by images and corresponding prices like OK Like
$myString = "ddb94-b_mgr3043.jpg,3800,83acc-b_mgr3059.jpg,4100";
I know that if I do:
$myArray = explode(',', $myString);
print_r($myArray);
I will get :
Array
(
[0] => ddb94-b_mgr3043.jpg
[1] => 3800
[2] => 83acc-b_mgr3059.jpg
[3] => 4100
)
But How could I split the string so I can have an associative array of the form?
Array
(
"ddb94-b_mgr3043.jpg" => "3800"
"83acc-b_mgr3059.jpg" => "4100"
)
Easier way to do like below:-
<?php
$myString = "ddb94-b_mgr3043.jpg,3800,83acc-b_mgr3059.jpg,4100";
$chunks = array_chunk(explode(',', $myString), 2); //chunk array into 2-2 combination
$final_array = array();
foreach($chunks as $chunk){ //iterate over array
$final_array[trim($chunk[0])] = trim($chunk[1]);//make key value pair
}
print_r($final_array); //print final array
Output:-https://eval.in/859757
Here is another approach to achieve this,
$myString = "ddb94-b_mgr3043.jpg,3800,83acc-b_mgr3059.jpg,4100,test.jpg,12321";
$arr = explode(",",$myString);
$temp = [];
array_walk($arr, function($item,$i) use (&$temp,$arr){
if($i % 2 != 0) // checking for odd values
$temp[$arr[$i-1]] = $item; // key will be even values
});
print_r($temp);
array_walk - Apply a user supplied function to every member of an array
Here is your working demo.
Try this Code... If you will receive all the key and value is equal it will work...
$myString = "ddb94-b_mgr3043.jpg,3800,83acc-b_mgr3059.jpg,4100";
$myArray = explode(',', $myString);
$how_many = count($myArray)/2;
for($i = 0; $i <= $how_many; $i = $i + 2){
$key = $myArray[$i];
$value = $myArray[$i+1];
// store it here
$arra[$key] = $value;
}
print_r($arra);
I want to sum each row of a multidimensional array :
$number = array
(
array(0.3,0.67, 0.3),
array(0.3,0.5,1),
array(0.67,0.67,0.3),
array(1,0.3,0.5)
);
The result what i want is like this :
row1 = 1.27
row2 = 1.8
row3 = 1.64
row4 = 1.8
I already tried this code :
for($i = 0; $i < 4; $i++) {
for($j = 0; $j < 5; $j++) {
$sumresult[] = array_sum($number[$i][$j]);
}
}
But it appear an error like this :
Warning: array_sum() expects parameter 1 to be array, double given in xxxx
array_sum needs array not values. Do like this:
for($i = 0; $i < 4; $i++) {
$sumresult[] = array_sum($number[$i]);
}
its because you are passing an value instead of the array containing it.
One correct solution would be:
$sumResult = array();
foreach($number as $values){
$sumResult []= array_sum($values);
}
print_r($sumResult);
Should do the trick ;)
It's easier to just map the array_sum() function to the array to sum the inner arrays:
$sumresult = array_map('array_sum', $number);
i am receiving the name from the $request in php.I want to do something like to add all the letters of the name in the array during the request e.g
$name=$_request['name'];
say $name='test';
i want to save it in an array in this format as array("t","e","s","t").
how can i do it ?
str_split is your friend.
$split_string = str_split($name);
It may be sufficient for you to access the string directly as an array, without the need to format the data:
$a = 'abcde';
echo $a[2];
Will output
c
However you won't be able to perform some array operations, such as foreach
see the php site
so it would be like
$name= 'test';
$arr1 = str_split($name);
would result in a array like:
Array
(
[0] => t
[1] => e
[2] => s
[3] => t
)
Here you go
$i = 0;
while(isset($name[$i])) {
$nameArray[$i] = $name[$i];
$i++;
}
Try this:
$letters = array();
for (int $i=0; $i < strlen($name); $i++){
$letters[] = $name[$i];
}
and you can access it with:
for (int $i=0; $i < strlen($letters); $i++){
$letters[$i];
}
I want to know if it is possible to take an array and insert the array's values into a bigger array, multiple times, so that the values of the smaller array fill up the bigger array.
Say array1 has values ([0 => 'a'],[1 => 'b'],[2 => 'c']), and array2 can hold 8 values. So, how would I take the values of array1 and insert them into array2 continuously until array2 runs out of space, so that array2 would have the values 'a','b','c','a','b','c','a','b'?
Thanks in advance,
~Hussain~
Essentially, you want to loop over and over the small array, adding each element to the new array until it has reached the desired size.
Consider this:
$max = 8;
$Orig_Array = array('a', 'b', 'c');
$Next_Array = array();
while True
{
foreach($Orig_Array as $v)
{
$Next_Array[] = $v;
if(count($Next_Array) >= $max)
break 2;
}
}
Assuming that your input array is indexed sequentially:
$len = count($input);
$output = array();
for ($i = 0; $i < MAX_SIZE; ++$i)
$output[] = $input[$i % $len];
$a = array('a','b','c');
$desired = 8;
$b = array();
for($i=0;$i<($desired/count($a))+1;++$i) $b = array_merge($b,$a);
array_splice($b,$desired);
Or
$a = array('a','b','c');
$desired = 8;
$b = array();
for($i=0;$i<$desired/count($a);++$i) $b = array_merge($b,$a);
for($i=0;$i<($desired-count($b)-1);++$i) $b[] = $a[$i];
The first one fills up an array so that it has at least desired number of elements and cuts off the rest. The second one fills up an array up the desired number of elements modulo original array size and adds up the rest.
Here's one using the input array's internal pointer, to keep things conceptually simple:
$input = array(1, 2, 3);
$size = 32;
$output = array();
for ( $i = 0; $i < $size; $i++ ) {
$curr = current($input);
if ( $curr === false ) {
reset($input);
$curr = current($input);
}
$output[] = $curr;
next($input);
}
print_r($output);die;