php array_push and array_intersect - php

I want to add value to array and then I want to use these arrays in array intersect. Codes are in bellow. Where am I doing mistake?
$array =['1,2,3,4','3,4,5','2,3'];
$arr2 = [];
$common = [];
for($i=0; $i<count($array); $i++)
{
$arr1 = [];
if($i==0)
{
array_push($arr1, $array[$i]);
array_push($arr2, $array[$i]);
$common = array_intersect($arr1,$arr2);
}
else
{
array_push($arr1, $array[$i]);
$common = array_intersect($arr1,$common);
}
print_r($common);
}
Output is :
Array (
[0] => 1,2,3,4
)
Array ( )
Array ( )
I want to be this :
Array (
[0] => 1,2,3,4
)
Array(
[0] => 3,4
)
Array(
[0] => 3
)
Thanks,

Try This
<?php
$array =['1,2,3,4','3,4,5','2,3'];
$arr1 = [];
for($i=0; $i<count($array); $i++)
{
$j='arr'.$i;
$j= [];
if($i==0){
array_push($j, $array[$i]);
}
else{
$a = explode(',',$array[$i-1]);
$b = explode(',',$array[$i]);
$c = array_intersect($a,$b);
$d= implode(',',$c);
array_push($j, $d);
}
echo "<pre>"; print_r($j);
}

You are misusing array_intersect. This method does works on values in an array not on a single value. To use it the way You want You should split your values by comma and insert them as separate values. For example:
value: '1,2,3,4' should be inserted as:
$array = ['1', '2', '3', '4'];
Solution (without loops etc):
<?php
$array =['1,2,3,4','3,4,5','2,3'];
$arr1 = array();
$arr2 = array();
$common = array();
$arr1 = explode(',', $array[0]);
$arr2 = explode(',', $array[1]);
$common =array_intersect($arr1, $arr2);
print_r($common);
$arr3 = explode(',', $array[2]);
$common2 = array_intersect($common, $arr3);
print_r($common2);
?>

Related

Split string with only one delimiting character into key-value pairs [duplicate]

This question already has answers here:
Convert backslash-delimited string into an associative array
(4 answers)
Closed 7 months ago.
I have a colon-delimited string like this:
"Part1:Part2:Part3:Part4"
With explode I can split the string into an array:
echo '<pre>';
print_r(explode(":", "Part1:Part2:Part3:Part4"));
echo '</pre>';
Output:
Array
(
[0] => Part1
[1] => Part2
[2] => Part3
[3] => Part4
)
But I need associative array elements like this:
Array
(
[Part1] => Part2
[Part3] => Part4
)
UPDATE
echo '<pre>';
list($key, $val) = explode(':', 'Part1:Part2:Part3:Part4');
$arr= array($key => $val);
print_r($arr);
echo '</pre>';
Result:
Array
(
[Part1] => Part2
)
Alternative solution using only array_* functions.
Collect all values that are going to be keys for the resultant array.
Collect all values that are going to be actual values for the resultant array.
Combine both using array_combine().
Snippet:
<?php
$str = "Part1:Part2:Part3:Part4";
$res = array_combine(
array_map(fn($v) => $v[0], array_chunk(explode(':',$str),2)),
array_map(fn($v) => $v[1], array_chunk(explode(':',$str),2))
);
Using a for loop, you could also use the modulo operator % and create the key in the if part.
The if clause will be true for the first item having the key first and then the value in the else part, toggeling the keys and the values.
$str = "Part1:Part2:Part3:Part4";
$parts = explode(':', $str);
$result = [];
for ($i = 0; $i < count($parts); $i++) {
$i % 2 === 0 ? $k = $parts[$i] : $result[$k] = $parts[$i];
}
print_r($result);
Output
Array
(
[Part1] => Part2
[Part3] => Part4
)
See a php demo
Try this
$string = "Part1:Part2:Part3:Part4";
$arr = explode(":", $string);
$key = "";
$i = 0;
$newArray = [];
foreach($arr as $row){
if($i == 0){
$key = $row;
$i++;
} else {
$newArray[$key] = $row;
$i = 0;
}
}
echo "<pre>";
print_r($newArray);
echo "</pre>";

how do i merge array values into single array?

I am trying to add(string) array values into single array, I have three array values like below:
Array ( [0] => 15 [1] => 16 )
Array ( [0] => jan [1] => feb )
Array ( [0] => 2012 [1] => 2012 )
and now i want those array in single array like below:
Array ( [0] => 15-jan-2012 [1] => 16-feb-2012 )
So how can i do this in php.
You need this custom code: Too simple, just a loop to access each and every array with there index and store in an array.
$d = array(15, 16);
$m = array("jan", "feb");
$y = array (2012, 2012);
$final = array();
for($i = 0; $i < count($d); $i++){
$final[] = $d[$i]. "-" .$m[$i]. "-" .$y[$i];
}
print_r($final);
Output:
Array ( [0] => 15-jan-2012 [1] => 16-feb-2012 )
you can do it using, array_merge_recursive, but has some difficulties.
ONLINE DEMO
Quick and dirty way, I am supposing that your each array has same length
$a = array ('15','16' );
$b = array ('jan','feb');
$c = array ('2012','2012');
$newArray = array();
for($i=0;$i<=count($a);$i++){
$newArray = $a[$i]. "-" .$b[$i]. "-" .$c[$i];
}
echo '<pre>';
print_r($newArray);
echo '</pre>';
You need a custom code like this one for example:
$arr = [];
$arr1 = [15, 16, 17, ...];
$arr2 = [jan, feb, ...];
$arr3 = [2012, 2012, ...];
for($i=0, $count = count($arr1); i<$count; i++)
{
$arr[] = "$arr1[$i]-arr2[$i]-arr3[$i]";
}
var_dump($arr);
Use array_column to get the required dates array, finally concat it using implode. Something like
$arr1 = array(15, 16);
$arr2 = array('jan', 'feb');
$arr3 = array(2012, 2012);
$date = array($arr1, $arr2, $arr3);
$dates = array(array_column($date, 0), array_column($date, 1));
$reqDate = array();
foreach ($dates as $dateVal) {
$reqDate[] = implode('-', $dateVal);
}
var_dump($reqDate); //your required output
You can write it all in one swoop like so:
$a = [15, 16];
$b = ['jan', 'feb'];
$c = [2012, 2012];
$dates = array_map(function($arr) {
return implode('-', $arr);
}, array_map(null, $a, $b, $c)));

Get values from second array where keys match

I have two arrays, the following:
$arr1 = array("Key1"=>1, "Key2"=>2, "Key3"=>3);
My second array is the following:
$arr2 = array("Key2", "Key3");
What I would like to get is the values where Key2 and Key3 matches. I would also like those values to be returned as an array so I end up with the following:
array(2,3)
Thanks for any help.
Just use of 3 three array functions to achieve this.
$arr1 = array("Key1"=>1, "Key2"=>2, "Key3"=>3);
$arr2 = array("Key2", "Key3");
$arr3 = array_values(array_intersect_key($arr1, array_flip($arr2)));
print_r($arr3);
The output:
Array ( [0] => 2 [1] => 3 )
$arr1 = array("Key1"=>1, "Key2"=>2, "Key3"=>3);
$arr2 = array("Key2", "Key3");
$result = array();
foreach($arr1 as $key => $value) {
if(in_array($key, $arr2)) {
array_push($result, $arr1[$key]);
}
}
var_dump($result);
or as mentioned in the comments:
$arr1 = array("Key1"=>1, "Key2"=>2, "Key3"=>3);
$arr2 = array("Key2", "Key3");
$result = array_intersect_key($arr1, array_flip($arr2));
var_dump($result);

php how to sort the values in multiple arrays in the order of frequency

I have an array containing multiple arrays like
$A = array();
$A[0] = array("1","2","3","4","5");
$A[1] = array("1","6","7","8");
$A[2] = array("0","1","3");
I want to sort the values in multiple arrays in the order of frequency and put them into another array let's say $B.
The values in $B is "1","1","1","3","3","0","2","4","5","6","7","8".
$A = array();
$A[0] = array("1","2","3","4","5");
$A[1] = array("1","6","7","8");
$A[2] = array("0","1","3");
//Merging above array in to one array
$merged = array_values(call_user_func_array('array_merge', $A));
//Getting occurrence count
$counts = array_count_values($merged);
//Sort by count
arsort($counts);
//Adding to required array
$B = array();
foreach ($counts as $k => $v)
for($i=1;$i<=$v;$i++)
$B[] = $k;
echo "<pre>";
print_r($B);
echo "</pre>";
Result
Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 3
[4] => 3
[5] => 0
[6] => 8
[7] => 7
[8] => 5
[9] => 2
[10] => 4
[11] => 6
)
First merge all arrays
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$resultado = array_merge($array1, $array2);
see -> http://php.net/manual/es/function.array-merge.php
Second sort the big array
arsort($resultado );
see -> http://php.net/manual/es/array.sorting.php
Use a hash table to count the frequency of each number, and then store them in the decreasing order of frequency in array $B, like this:
$hash_table = array();
foreach($A as $array){
foreach($array as $value){
if(empty($hash_table[$value])){
$hash_table[$value] = 1;
}else{
$hash_table[$value] += 1;
}
}
}
arsort($hash_table);
$B = array();
foreach($hash_table as $key => $value){
for($i = 0; $i < $value; ++$i){
$B[] = $key;
}
}
var_dump($B); // to see the contents of array $B
If order of same occurance count items isn't important, you can use:
// Merge all arrays
$counts = array_count_values(call_user_func_array('array_merge', $A));
// Sort by occurance
arsort($counts);
// Add [value] to new array [occurance] times
$B = array();
array_walk($counts, function($occurances, $value) use (&$B){
for($i=0;$i<$occurances;$i++) $B[] = $value;
});
echo implode(',', $B);
Output
1,1,1,3,3,0,8,7,5,2,4,6
Array print in order of count and index:
$temp = array();
foreach($A as $b){
foreach($b as $c){
if(isset($tmep[$c])){
$tmep[$c]++;
}else{
$tmep[$c] = 1;
}
}
}
function SortArrayByKeyThanValue (&$pArray, $pSortMethodForKey = SORT_ASC, $pSortMethodForValue = SORT_DESC){
# check user input: sorting is not necessary
if (count($pArray) < 2)
return;
# define $k and $v as array_multisort() needs real variables, as user input is put by reference
$k = array_keys ($pArray);
$v = array_values($pArray);
array_multisort(
$v, $pSortMethodForValue,
$k, $pSortMethodForKey
);
$pArray = array_combine($k, $v);
}
SortArrayByKeyThanValue($tmep);
$B = array();
array_walk($tmep, function($occurances, $value) use (&$B){
for($i=0;$i<$occurances;$i++) $B[] = $value;
});
echo implode(',', $B);

For Loop Formulae

I have the following and would want another result.
String = A,B,C,D
Trying to get an array of
A
A,B
A,B,C
A,B,C,D
My current code
$arrayA = explode(',', $query);
$arrSize = count($arrayA);
for ($x=0; $x<$arrSize; ++$x) {
for ($y=0; $x==$y; ++$y) {
array_push($arrayB,$arrayA[$x]);
$y=0;
}
}
Here's one way to do it using array_slice:
$str = 'A,B,C,D';
$strArr = explode(',', $str);
$newArr = array();
for($i=1; $i<=sizeof($strArr); $i++)
{
$newArr[] = implode( ',' , array_slice($strArr, 0, $i) );
}
print_r($newArr);
Outputs:
Array
(
[0] => A
[1] => A,B
[2] => A,B,C
[3] => A,B,C,D
)
Online demo here.
$test="a,b,c,d,e";
$arrayA = explode(',', $test);
$res=array();
$aux=array();
foreach($arrayA as $c){
$aux[]=$c;
$res[]=$aux;
}
i have not tested yet, but i think u catch the idea ;)

Categories