PHP grouping single array - php

i want to convert single array to group array like with this:
group_1
1,2,3,4
group_2
5,6,7,8
from single array like with this:
$arr=array('1','2','3','4','5','6','7','8');
each group must be have 4 andis. and i can not programing that.
i want to have this result:
array (
'group_1'=>('1','2','3','4')
'group_2'=>('5','6','7','8')
)
my simple and wrong code:
<?php
$singleArray= array(
"arr_1",
"arr_2",
"arr_3",
"arr_4",
"arr_5",
"arr_6",
"arr_7",
"arr_8",
);
$groups = array( 'group_1','group_2' );
$groupArray = array();
foreach( $singleArray as $key=>$arr ){
if( $key != ['3','7'] ){
$groupArray[][] = $arr;
}
}
?>

Use array_chunk() to split your array into two pieces, each containing 4 elements. Now use array_combine() to create the result array using $groups as keys and the sliced array as values:
$result = array_combine($groups, array_chunk($singleArray, 4));
Demo

Related

How to use str_repeat to repeat a string from an array giving an index of each loop of the str_repeat [duplicate]

This question already has answers here:
How do I create a comma-separated list from an array in PHP?
(11 answers)
Closed 2 years ago.
I'm trying to concatenate array keys (which are originally a class properties). So what I did is:
echo '<pre>'.print_r(array_keys(get_object_vars($addressPark)),TRUE).'</pre>';
Outputs:
Array
(
[0] => streetAddress_1
[1] => street_address_2
[2] => city_name
[3] => subdivision_name
[4] => country_name
)
This is how I get the AddressPark object's properties names.
$arr = array_keys(get_object_vars($addressPark));
$count = count($arr);
I want to access the object properties by index, that is why I used array_keys.
$props = str_repeat("{$arr[$count-$count]},",$count-2).$arr[$count-1];
echo $props;
The results is:
streetAddress_1,streetAddress_1,streetAddress_1,country_name
It repeats $arr[0] = 'streetAddress_1' which is normal because in every loop of the str_repeat the index of $arr is $count-$count = 0.
So what I exactly want str_repeat to do is for each loop it goes like: $count-($count-0),$count-($count-1) ... $count-($count-4). Without using any other loop to increment the value from (0 to 4).
So is there another way to do it?
No, you cannot use str_repeat function directly to copy each of the values out of an array into a string. However there are many ways to achieve this, with the most popular being the implode() and array_keys functions.
array_keys extracts the keys from the array. The following examples will solely concentrate on the other part of the issue which is to concatenate the values of the array.
Implode
implode: Join array elements with a string
string implode ( string $glue , array $pieces )
Example:
<?php
$myArray = ['one','two','three'];
echo implode(',', $myArray);
// one,two,three
echo implode(' Mississippi;', $myArray);
// one Mississippi; two Mississippi; three Mississippi;
Foreach
foreach: The foreach construct provides an easy way to iterate over arrays, objects or traversables.
foreach (array_expression as $key => $value)
...statement...
Example:
<?php
$myArray = ['one','two','three'];
$output = '';
foreach ($myArray as $val) {
$output .= $val . ',';
}
echo $output;
// one,two,three,
Notice that on this version we have an extra comma to deal with
<?php
echo rtrim($output, ',');
// one,two,three
List
list: Assign variables as if they were an array
array list ( mixed $var1 [, mixed $... ] )
Example:
<?php
$myArray = ['one','two','three'];
list($one, $two, $three) = $myArray;
echo "{$one}, {$two}, {$three}";
// one, two, three
Note that on this version you have to know how many values you want to deal with.
Array Reduce
array_reduce: Iteratively reduce the array to a single value using a callback function
mixed array_reduce ( array $array , callable $callback [, mixed $initial = NULL ] )
Example:
<?php
$myArray = ['one', 'two', 'three'];
echo array_reduce($myArray, function ($carry, $item) {
return $carry .= $item . ', ';
}, '');
// one, two, three,
This method also causes an extra comma to appear.
While
while: while loops are the simplest type of loop in PHP.
while (expr)
...statement...
Example:
<?php
$myArray = ['one', 'two', 'three'];
$output = '';
while (!empty($myArray)) {
$output .= array_shift($myArray);
$output .= count($myArray) > 0 ? ', ' : '';
}
echo $output;
// one, two, three
Notice that we've handled the erroneous comma in the loop. This method is destructive as we alter the original array.
Sprintf and String Repeat
sprintf: My best attempt of actually using the str_repeat function:
<?php
$myArray = ['one','two','three'];
echo rtrim(sprintf(str_repeat('%s, ', count($myArray)), ...$myArray), ', ');
// one, two, three
Notice that this uses the splat operator ... to unpack the array as arguments for the sprintf function.
Obviously a lot of these examples are not the best or the fastest but it's good to think out of the box sometimes.
There's probably many more ways and I can actually think of more; using array iterators like array_walk, array_map, iterator_apply and call_user_func_array using a referenced variable.
If you can think of any more post a comment below :-)

In php How i divide a array by user input for make it to another some arrays

Suppose my array is:
$letters = array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z");
and user input is:
$number = "4";
Now how i convert this array on look like that:
$array1 = array("a","b","c","d");
$array2 = array("e","f","g","h");
$array3 = array("i","j","k","l");
Try http://php.net/array_chunk
If you want to split the array in 4 then your code should look like this.
$output_array=array_chunk($letters, 4);
This will return you two dimensional array having chunks of array of 4 key,value pairs.
Use array_chunk — Split an array into chunks:
Ex
array array_chunk ( array $array , int $size [, bool $preserve_keys = false ] )
So Use
array_chunk($letters,4,true)

Remove array elements based on value supplied

If I had an array like this...
array('1','2','3','4','10')
... how could I remove elements before the element whose value I supply.
For example:
If I supplied 1 then array = (1,2,3,4,10)
If it were 2 then array = (2,3,4,10) //Remove the numbers before 2
If it were 3 then array = (3,4,10) //Remove the numbers before 3
If it were 4 then array = (4,10) //Remove the numbers before 4
If it were 10 then array = (10) //Remove all before the 10
I'm currently thinking of doing with using if else. But is there a way to do this using some kind of php array function itself.
Make use of array_search and array_slice
<?php
$arr=array_slice($arr, array_search('4',array('1','2','3','4','10')));
print_r($arr);
OUTPUT :
Array
(
[0] => 4
[1] => 10
)
Demo
Maybe this would help:
$myArray = array('1','2','3','4','10');
$x=3;
$myArray = array_splice($myArray, array_search($x, $myArray), count($myArray));
$myArray = array('1','2','3','4','10');
$value = 3;
$key = array_search($value, $myArray);
$myNewArray = array_splice($myArray, 0, $key);
$array = array_filter($array, function($item) use ($filterItem) {
return $item !== $filterItem;
});
Will filter out every item equal to $filterItem. array_filter on php.net

List of Arrays intersect

I have some arrays called
$array[1], $array[2] etc.
$array[1] is something like array(1,2,3) and $array[2] is sth. like array(2,3,4)
now I want to have alle numbers which are in all arrays.
I want to use
array_intersect($array[1],$array[2])
for this.
BUT I have maybe 2 or 3 or 4 of this array. Is it possible to create a string like
$list_of_array = $array[1],$array[2];
and make a
$result = array_intersect($list_of_arrays)
?
For such behaviour with variable amount of arrays, you can use call_user_func_array:
$array_list = array($array[1],$array[2],$array[3]);
$intersect = call_user_func_array('array_intersect',$aarray_list);
Test
$array_list = array(array(1,2,3), array(2,3,4,5), array(3,7,"a"));
$result = call_user_func_array('array_intersect',$array_list);
print_r($result);
Returns
Array ( [2] => 3 )
Yes, you can use call_user_func_array():
As the name suggests, you can use this function to call a user function and apply it with the parameters in the given array:
$result = call_user_func_array('array_intersect',$list_of_arrays);
Here, the first parameter is the name of the function callback, and second one is our array.
Assuming you have the $array filled with your input arrays, you can do:
$list_of_arrays = $array;
$result = call_user_func_array('array_intersect', $list_of_arrays);
Output:
Array
(
[2] => 3
)
Demo!

How to delete duplicates in an array?

How can I delete duplicates in array?
For example if I had the following array:
$array = array('1','1','2','3');
I want it to become
$array = array('2','3');
so I want it to delete the whole value if two of it are found
Depending on PHP version, this should work in all versions of PHP >= 4.0.6 as it doesn't require anonymous functions that require PHP >= 5.3:
function moreThanOne($val) {
return $val < 2;
}
$a1 = array('1','1','2','3');
print_r(array_keys(array_filter(array_count_values($a1), 'moreThanOne')));
DEMO (Change the PHP version in the drop-down to select the version of PHP you are using)
This works because:
array_count_values will go through the array and create an index for each value and increment it each time it encounters it again.
array_filter will take the created array and pass it through the moreThanOne function defined earlier, if it returns false, the key/value pair will be removed.
array_keys will discard the value portion of the array creating an array with the values being the keys that were defined. This final step gives you a result that removes all values that existed more than once within the original array.
You can filter them out using array_count_values():
$array = array('1','1','2','3');
$res = array_keys(array_filter(array_count_values($array), function($freq) {
return $freq == 1;
}));
The function returns an array comprising the original values and their respective frequencies; you then pick only the single frequencies. The end result is obtained by retrieving the keys.
Demo
Try this code,
<?php
$array = array('1','1','2','3');
foreach($array as $data){
$key= array_keys($array,$data);
if(count($key)>1){
foreach($key as $key2 => $data2){
unset($array[$key2]);
}
}
}
$array=array_values($array);
print_r($array);
?>
Output
Array ( [0] => 2 [1] => 3 )
PHP offers so many array functions, you just have to combine them:
$arr = array_keys(array_filter(array_count_values($arr), function($val) {
return $val === 1;
}));
Reference: array_keys, array_filter, array_count_values
DEMO
Remove duplicate values from an array.
array_unique($array)
$array = array(4, "4", "3", 4, 3, "3");
$result = array_unique($array);
print_r($result);
/*
Array
(
[0] => 4
[2] => 3
)
*/

Categories