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;
}
Related
What would be the most efficient PHP way to get unique values from an array of arrays and sort them by number of occurrences from most frequent to least?
Example input array:
Array
(
[0] => Array
(
[0] => A
[1] => B
[2] => C
[3] => D
)
[1] => Array
(
[0] => A
[1] => C
[2] => D
)
[2] => Array
(
[0] => C
[1] => F
[2] => X
)
)
Would result in this output array:
Array
(
[0] => C // 3
[1] => A // 2
[2] => D // 2
[3] => B // 1
[4] => F // 1
[5] => X // 1
)
The alphabetical order of values with same number of occurrences is not important.
So far I'm merging the array of arrays:
$all_posts = call_user_func_array( 'array_merge', $results );
Then creating a new array where values become keys. And values are the number of times they occur in the original array of arrays.
$posts_by_count = array();
foreach( $all_posts as $apost ) {
$posts_by_count[ $apost ] = 0;
foreach( $results as $tag_posts ) {
if( in_array( $apost, $tag_posts ) ) {
$posts_by_count[ $apost ]++;
}
}
}
Then I can sort by value
arsort($posts_by_count);
And create a new array where keys become values again.
$sorted_posts = array();
foreach($posts_by_count as $k => $v) {
$sorted_posts[] = $k;
}
pprint( $sorted_posts );
What would be a more efficient way to do that?
The simplest I can come up with is to start with the array_merge(), but using the splat (...) to merge all of the arrays. Then use the inbuilt array_count_values() to summarize the values and then arsort() to sort them...
$all_posts = array_merge(...$results );
$posts_by_count = array_count_values($all_posts);
arsort($posts_by_count);
This gives the output of...
Array
(
[C] => 3
[A] => 2
[D] => 2
[B] => 1
[F] => 1
[X] => 1
)
using
print_r(array_keys($posts_by_count));
gives...
Array
(
[0] => C
[1] => A
[2] => D
[3] => B
[4] => F
[5] => X
)
That's simple, first iterate to count occurences, finally use arsort() to sort it by value in descending order:
<?php
// sample data
$arr = [
['A', 'B', 'C', 'D'],
['A', 'C', 'D'],
['C', 'F', 'X']
];
// counting
$newArr = [];
foreach ($arr as $subarr) {
foreach ($subarr as $char) {
$newArr[$char] = (!array_key_exists($char, $newArr))
? 1
: $newArr[$char] = $newArr[$char] + 1;
}
}
// sort by value in DESC order
arsort($newArr);
// To get exactly what you want (without counting) just iterate $newArr and writ is as a $flatArr
$flatArr = [];
foreach ($newArr as $index => $item) {
$flatArr[] = $index;
}
// or with array_keys which _may_ be unstable #see: https://stackoverflow.com/q/10336363/1066240
$flatArrArrayKeys = array_keys($newArr);
// output
$newArrHr = print_r($newArr, 1);
$flatArrHr = print_r($flatArr, 1);
echo "<pre>OUTPUT:
With count:
$newArrHr
As flat array:
$flatArrHr
As flat array with array_keys()
$flatArrArrayKeys
";
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
)
)
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);
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 )
I have a multidimensional array that looks like this:
Array
(
[0] => Array
(
[0] => Array
(
[id] => 3
)
[1] => Array
(
[id] => 1
)
[2] => Array
(
[id] => 2
)
[3] => Array
(
[id] => 5
)
[4] => Array
(
[id] => 4
)
)
[1] => Array
(
[0] => Array
(
[id] => 1
)
[1] => Array
(
[id] => 3
)
[2] => Array
(
[id] => 4
)
[3] => Array
(
[id] => 5
)
)
[2] => Array
(
[0] => Array
(
[id] => 3
)
)
)
I need to find a way to return the intersecting value(s). In this case that would be
[id] => 3
The length of the array could be different, so I can't just use array_intersect().
This would be simple if your arrays contained only integers, but as they contain an another array, it gets a bit more complicated. But this should do it:
function custom_intersect($arrays) {
$comp = array_shift($arrays);
$values = array();
// The other arrays are compared to the first array:
// Get all the values from the first array for comparison
foreach($comp as $k => $v) {
// Set amount of matches for value to 1.
$values[$v['id']] = 1;
}
// Loop through the other arrays
foreach($arrays as $array) {
// Loop through every value in array
foreach($array as $k => $v) {
// If the current ID exists in the compare array
if(isset($values[$v['id']])) {
// Increase the amount of matches
$values[$v['id']]++;
}
}
}
$result = array();
// The amount of matches for certain value must be
// equal to the number of arrays passed, that's how
// we know the value is present in all arrays.
$n = count($arrays) + 1;
foreach($values as $k => $v) {
if($v == $n) {
// The value was found in all arrays,
// thus it's in the intersection
$result[] = $v;
}
}
return $result;
}
Usage:
$arrays = array(
array(array('id' => 3), array('id' => 1), array('id' => 2), array('id' => 5), array('id' => 4)),
array(array('id' => 1), array('id' => 3), array('id' => 4), array('id' => 5)),
array(array('id' => 3))
);
print_r(custom_intersect($arrays));
Result:
Array
(
[0] => 3
)
This function isn't perfect: if you have duplicate ID's in one array, it will not work. That would require a bit more code to first make the array values unique, but this will probably work in your case.
You can use array_uintersect() to get the intersection of arrays using a custom comparison function. You have to call it with call_user_func_array() though, as it expects each array as a separate argument:
//build list of parameters for array_uintersect()
$params = array_merge($input, array('compare_func'));
$result = call_user_func_array('array_uintersect', $params);
function compare_func($a, $b) {
return $a['id'] - $b['id'];
}
You can't simply call array_intersect() with call_user_func_array(), because it seems to compare arrays by comparing their string representation (which will always be 'Array').
$a = array(4,3);
$b = array(4,3,2,1);
$c = array(1,2,3,4,5);
$d = array(5,4,3);
$array = array($a,$b,$c,$d);
for ($i=0; $i<count($array); $i++){
if ($i==0){
$array2 = $array[$i];
} else {
$array2 = array_intersect($array2, $array[$i]);
}
}
print_r($array2);`
Result:
3,4
As mentioned in one of the comments of the php.net website (array_intersect function).
$a = array(1,2,3,4,5,2,6,1); /* repeated elements --> $a is not a set */
$b = array(0,2,4,6,8,5,7,9,2,1); /* repeated elements --> $b is not a set */
$ua = array_merge(array_unique($a)); /* now, $a is a set */
$ub = array_merge(array_unique($b)); /* now, $b is a set */
$intersect = array_merge(array_intersect($ua,$ub));
This will return this array:
Array
(
[0] => 1
[1] => 2
[2] => 4
[3] => 5
[4] => 6
)