This question already has answers here:
Cartesian Product of N arrays
(10 answers)
Closed 8 years ago.
Let's assume I have an two arrays and I want to merge every value with the other value of the array.
Array 1
array (size=2)
0 => 1
1 => 2
Array 2
array (size=2)
0 => 3
1 => 4
Wanted result array / string:
array (size=4)
0 => '1,3'
1 => '1,4'
2 => '2,3'
3 => '2,4'
I can't get my head around it. Obviously I would need to merge every one array key/value with the other ones. Is there a more elegant way then doing this in a while/foreach loop?
You need a foreach loop inside a foreach loop. (Actualy, you will have to loop through both arrays to get a concatenated product of both arrays, you don't actually need two foreach loops). You could mix: whiles, foreach, for, or php filter/intersect array functions
Example
$array1 = array(1,2);
$array2 = array(3,4);
$result = array();
foreach ($array1 as $item1){
foreach($array2 as $item2){
$result[] = $item1.','.$item2;
}
}
https://eval.in/215001
your result array Length will be array1.Length * array2.Length
2d arrays
You could also put an array inside an array like this:
$array1 = array(1,2);
$array2 = array(3,4);
$result = array();
foreach ($array1 as $item1){
foreach($array2 as $item2){
$result[] = array($item1, $item2);
}
}
//$result[0][0] = 1 -- $result[0][1] = 3
//$result[1][0] = 1 -- $result[1][1] = 4
//$result[2][0] = 2 -- $result[2][1] = 3
//$result[3][0] = 2 -- $result[3][1] = 4
We call this a 2d (2 dimensional) array, because you could grapicly display this as a grid, like displayed here above. If you would put an Array, inside an Array inside an Array, you would call this a 3 dimensional array, etc.
print_r($result); in php:
Array
(
[0] => Array
(
[0] => 1
[1] => 3
)
[1] => Array
(
[0] => 1
[1] => 4
)
[2] => Array
(
[0] => 2
[1] => 3
)
[3] => Array
(
[0] => 2
[1] => 4
)
)
try
$a= array ('0' => 1,'1' => 2);
$b= array ('0' => 3,'1' => 4);
for($i=0; $i<count($a); $i++) {
for($j=0; $j<count($b); $j++) {
$newarr[]= $a[$i].','.$b[$j];
}
}
print_r($newarr);//Array ( [0] => 1,3 [1] => 1,4 [2] => 2,3 [3] => 2,4 )
$a=array('1','2');
$b=array('3','4');
$res=array();
for($i=0;$i<count($a);$i++)
{
foreach($b as $bb)
{
$res[]=strval($a[$i].','.$bb);
}
}
print_r($res);//output=Array ( [0] => 1,3 [1] => 1,4 [2] => 2,3 [3] => 2,4 )
Related
This question already has answers here:
Merge two arrays as key value pairs in PHP
(3 answers)
Closed 5 months ago.
I have two arrays:
Array ( [0] => label [1] => data )
Array ( [0] => 1 [1] => 2 )
And I need merge them in a array like this:
Array ( [0] => Array ( [label] => 1 [data] => 2 ) )
I have tried:
for ($i=0; $i < count($inputs); $i++) {
$new = array($cols[$i] => $inputs[$i]);
$data[] = $new;
}
Any help is welcome ;)
You can simply use array_combine:
Creates an array by using one array for keys and another for its
values
$arr1 = array(0 => 'label', 1 => 'data');
$arr2 = array(0 => 1, 1 => 2);
$arr3 = array_combine($arr1, $arr2);
print_r($arr3);
Result:
Array
(
[label] => 1
[data] => 2
)
Try it
You can do it like so if you want to use a loop
$array1 = ['label', 'data'];
$array2 = [1, 2];
$array_merged = [];
foreach($array1 as $key => $value) {
$array_merged[$value] = $array2[$key];
}
var_dump($array_merged);
http://sandbox.onlinephpfunctions.com/code/c4e5bc71df53ebdafb0a54d43c3eadb4ea4cd241
I am trying to split array data into multiple arrays based on change in data value at known position (column).
$input = array(
array(1,2,3),
array(4,5,3),
array(7,8,4),
array(9,10,4),
array(11,12,4)
);
Here column 3 changes values from 3 to 4
and expected result is to have 2 arrays
$out1 = array(array(1,2,3),array(4,5,3));
$out2 = array(array(7,8,4), array(9,10,4), array(11,12,4));
since number of rows are variable, cannot use array_chunk
since column 3 values are variable, cannot use array_filter
number of output arrays are also variable.
trying splice but failing...
You can use array_reduce to make new array, where index will be equal to last numbers in items
$new = array_reduce($input, function($c, $x) { $c[$x[2]][] = $x; return $c; }, [] );
$out1 = $new[3];
$out2 = $new[4];
demo
But if array is not sorted and you want to split at points of changing that number, the code can be
$i = -1;
$last = null;
$new = [];
foreach($input as $x) {
if ($x[2] != $last) {
$i++;
$last = $x[2];
}
$new[$i][] = $x;
}
demo
You can use split index with index of array,
$out1 = $out2 = [];
$splitIndex = 2;
foreach($input as $k => $v){
if($k < $splitIndex){
$out1[] = $v;
}else{
$out2[] = $v;
}
}
print_r($out1);
print_r($out2);
Working demo
Output:-
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[0] => 4
[1] => 5
[2] => 3
)
)
Array
(
[0] => Array
(
[0] => 7
[1] => 8
[2] => 4
)
[1] => Array
(
[0] => 9
[1] => 10
[2] => 4
)
[2] => Array
(
[0] => 11
[1] => 12
[2] => 4
)
)
i have one array and elements like:-
enter code here
$array = array('1', '2', '3', '4','5','6'); // n number of elements
echo "<pre>"; print_r($array); die;
when i print this array its give me this result
enter code here
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
i want output something like:-
enter code here
Array
(
[0] => Array
(
[0] => 1
[1] => 2
)
[1] => Array
(
[0] => 3
[1] => 4
)
[2] => Array
(
[0] => 5
[1] => 6
)
)
Can anyone help me how i can make two group of elements
Not:- array elements are dynamic it may be n number of elements
As you are requesting an example using foreach, you can use the modulus % mathematics operator to check every x.
$array = array( 1, 2, 3, 4, 5, 6 );
$tmp = array(); // temporarily hold values
$newarray = array(); // new array to hold final results
foreach ($array as $key=>$value) {
$tmp[] = $value; // add this value to temporary variable
if (($key + 1) % 2 == 0) {
$newarray[] = $tmp; // add temporary variable to new array
$tmp = array(); // reset temporary variable
}
}
// add remaining from odd number (if any)
if(count($tmp) > 0) {
$newarray[] = $tmp;
}
Does anyone know how I can create an Array?
$string = '3-1-0-1.11,3-1-1-1.12,3-1-2-1.13,3-1-3-1.14,3-2-0-1.02,3-2-1-1.03,3-2-2-1.04,3-2-3-1.05,3-2-4-1.06,3-3-0-3.23,3-3-1-3.24,3-3-2-3.25,3-3-3-3.26';
$array = explode(',', $string);
$last_entry = null;
foreach ($array as $current_entry) {
$first_char = $current_entry[2]; // first Sign
if ($first_char != $last_entry) {
echo '<h2>'. $first_char . '</h2><br>';
}
echo $current_entry[4] . '<br>';
$last_entry = $first_char;
}
I need an Array like this:
Array
(
[1] => Array
(
[0] => 0
[1] => 1
[2] => 2
)
[2] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
)
[3] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
)
The first number 3 and other numbers 3 after comma are not important.
Important numbers are second and third numbers in values of $array.
I need categories. Example: if the first (second) number is 1 create Category 1 and subcategory 1 where first (second) number actual is 1.
To create an an array, you need to declare it using array() feature. Below I have created a blank array.
$array = array();
An array with values looks like this
$array = array("string", "string2", "string3");
To add values in an array, you use the array_push method.
array_push($array, "string4");
On multidimensional arrays, declare the array then add the inner array, below is objct oriented
$array = array("string"=>array("innerstring", "innerstring2"), "string2" => array("innerstring3", "innerstring4"), "string3" => array("innerstring5", "innerstring6"));
and procedural
$array=array(array("string", "innerstring", "innerstring2",), array("string2", "innerstring3", "innerstring4"), array("string3", "innerstring5", "innerstring6"));
Try next script:
$string = '3-1-0-1.11,3-1-1-1.12,3-1-2-1.13,3-1-3-1.14,3-2-0-1.02,3-2-1-1.03,3-2-2-1.04,3-2-3-1.05,3-2-4-1.06,3-3-0-3.23,3-3-1-3.24,3-3-2-3.25,3-3-3-3.26';
foreach(explode(',', $string) as $tpl) {
$tpl = explode('-', $tpl);
$tpl[3] = explode('.', $tpl[3]);
$result[$tpl[1]][$tpl[2]][$tpl[3][0]] = !empty($tpl[3][1]) ? $tpl[3][1] : null;
}
var_dump($result);
I am looking at trying to do an array_merge with these arrays but I need to be able to count how many times a particular value in the array appears and give me that data back.
Here are the original arrays
Array
(
[0] => this
[1] => that
)
Array
(
[0] => this
[1] => that
[2] => some
)
Array
(
[0] => some
[1] => hello
)
Ultimately I would like it to look like this
Array
(
[this] => 2
[that] => 2
[some] => 2
[hello] = > 1
)
That would ultimately allow me to get the key and value I need. I tried 'array_unique` in this process but realized that I may not be able to count the instances of each array that they appear since this would just simple remove them all but one.
I tried something list this
$newArray = array_count_values($mergedArray);
foreach ($newArray as $key => $value) {
echo "$key - <strong>$value</strong> <br />";
}
but I am getting results like this
Array
(
[this] => 2
[that] => 2
[some] => 2
[hello] = > 1
[this] => 3
[that] => 3
[some] => 3
[hello] = > 2
[this] => 2
[that] => 2
[some] => 2
[hello] = > 1
)
Use array_count_values():
$a1 = array(0 => 'this', 1 => 'that');
$a2 = array(0 => 'this', 1 => 'that', 2 => 'some');
$a3 = array(0 => 'some', 1 => 'hello');
// Merge arrays
$test = array_merge($a1,$a2,$a3);
// Run native function
$check = array_count_values($test);
echo '<pre>';
print_r($check);
echo '</pre>';
Gives you:
Array
(
[this] => 2
[that] => 2
[some] => 2
[hello] => 1
)
EDIT: As noted by AlpineCoder:
"This will work only in the case of input arrays using numeric (or unique) keys (since array_merge will overwrite values for the same non-integer key)."
$res = array();
foreach ($arrays as $array) {
foreach ($array as $val) {
if (isset($res[$val])) {
$res[$val]++;
} else {
$res[$val] = 1;
}
}
}
As tyteen4a03 mentioned, use nested foreach loops:
$arr1 = array('foo', 'bar');
$arr2 = array('foo', 'bar', 'baz');
$arr3 = array('baz', 'bus');
$result = array();
foreach(array($arr1, $arr2, $arr3) as $arr) {
foreach ($arr as $value) {
if (!isset($result[$value])) {
$result[$value] = 0;
}
++$result[$value];
}
}
print_r($result);
The outer foreach goes through each set of items (i.e. each array) and the inner foreach loop goes through each item in each set. If the item isn't in the $result array yet, create the key there.
Result:
Array
(
[foo] => 2
[bar] => 2
[baz] => 2
[bus] => 1
)