I have an array of numeric subarrays. I want to sort all the subarrays, and then sort the whole array, and remove duplicates. Using sort($val) doesn't work, so I found the following workaround with $derp, which I find insanely stupid:
$arr = array( array(5,6), array(1,2), array(6,5) );
foreach ($arr as $key => $val) {
$derp = $val;
sort($derp);
$arr[$key] = $derp;
}
sort($arr);
$arr = array_map("unserialize", array_unique(array_map("serialize", $arr)));
The result is array( array(1,2), array(5,6) ). Is that is the correct way to do this in PHP, or is there a better and shorter way?
I created a pastebin as a response to the first answer: pastebin.com/Y5vNvKKL
This question is not anymore just about a less goofy way to write this: Now the question is:Why does sort() in array_work() not give the same result as sort() in foreach?
By the way: This is about finding the partitions of multisets.
I'd approach it like this:
array_walk($arr, 'sort');
$deduped = array();
foreach ($arr as $val) {
$deduped[serialize($val)] = $val;
}
$arr = array_values($deduped);
Related
I have a multi dimension array that I want to merge all the inside arrays into one singer dimension array, I have tried array_merge with foreach but it doesn't help.
Example Array:
$nums = array (
array(1,2,3),
array(4,5,6),
array(7,8,9)
);
What I did but get an empty array
$newArr = [];
foreach ($nums as $value) {
array_merge($newArr, $value);
}
Expectation
$newArr = array(1,2,3,4,5,6,7,8,9)
You could use the function array_merge() this way :
$newArr = array_merge(...$nums)
It would make your code lighter and avoid the use of a foreach loop.
array_merge returns the results of the merge rather than acting on the passed argument like sort() does. You need to be doing:
$newArr = array_merge($newArr, $value);
I have this kind of an array containing single-element arrays:
$array = [[88868], [88867], [88869], [88870]];
I need to convert this to one dimensional array.
Desired output:
[88868, 88867, 88869, 88870]
Is there any built-in/native PHP functionality for this array conversion?
For your limited use case, this'll do it:
$oneDimensionalArray = array_map('current', $twoDimensionalArray);
This can be more generalized for when the subarrays have many entries to this:
$oneDimensionalArray = call_user_func_array('array_merge', $twoDimensionalArray);
The PHP array_mergeĀDocs function can flatten your array:
$flat = call_user_func_array('array_merge', $array);
In case the original array has a higher depth than 2 levels, the SPL in PHP has a RecursiveArrayIterator you can use to flatten it:
$flat = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)), 0);
See as well: Turning multidimensional array into one-dimensional array
try:
$new_array = array();
foreach($big_array as $array)
{
foreach($array as $val)
{
array_push($new_array, $val);
}
}
print_r($new_array);
$oneDim = array();
foreach($twoDim as $i) {
$oneDim[] = $i[0];
}
Yup.
$values = array(array(88868), array(88867), array(88869), array(88870));
foreach ($values as &$value) $value = $value[0];
http://codepad.org/f9KjbCCb
foreach($array as $key => $value){
//check that $value is not empty and an array
if (!empty($value) && is_array($value)) {
foreach ($value as $k => $v) {
//pushing data to new array
$newArray[] = $v;
}
}
}
For a two dimensional array this works as well:
array_merge(...$twoDimensionalArray)
While some of the answers on the page that was previously used to close this page did have answers that suited this question (like array_merge(...$array)). There are techniques for this specific question that do not belong on the other page because of the input data structure.
The sample data structure here is an array of single-element, indexed arrays.
var_export(array_column($array, 0));
Is all that this question requires.
If you ever have a daft job interview that asks you to do it without any function calls, you can use a language construct (foreach()) and use "array destructuring" syntax to push values into a result variable without even writing a body for the loop. (Demo)
$result = [];
foreach ($array as [$result[]]);
var_export($result);
Laravel also has a flattening helper method: Arr::flatten()
What is the best way you think to shuffle a multi-dimensional array in the following structure, so that question-answer pairs are separated?
$myArray = array(
array('question' => 'q1', 'answer' => 'a1'),
array('question' => 'q2', 'answer' => 'a2'),
array('question' => 'q3', 'answer' => 'a3')
//...
//...
);
What I need is to turn this:
q1-a1, q2-a2, q3-a3...
into this:
q3-a2, q4-a3, q1-a9...
I get this array from a questions database. I want to display question-answer pairs but shuffled obviously. I have a few solutions in my mind, just curious for clever ways to do it ;)
Well you could just simply get the questions and answers, shuffle them, then reapply:
$q = $a = array();
foreach ($myArray as $value) {
$q[] = $value['question'];
$a[] = $value['answer'];
}
shuffle($q);
shuffle($a);
foreach($myArray as $key => &$value) {
$value['question'] = $q[$key];
$value['answer'] = $a[$key];
}
echo '<pre>';
print_r($myArray);
You could also use array_collumn() if available (PHP 5 >= 5.5.0):
$q = array_column($myArray, 'question');
$a = array_column($myArray, 'answer');
PHP has a plethora amount of built-in array functions. Using a combination of these functions, you could create a custom shuffle function that uses array_keys, array_values, shuffle and array_combine internally. Try the following:
// Create a copy of the original array to key
// for processing later...
$originalArray = $myArray;
function shuffleAll($myArray) {
// Pull the keys into an array and
// pull the values into another
// array...
$keys = array_keys($myArray);
$values = array_values($myArray);
// Shuffle the arrays independently...
shuffle($keys);
shuffle($values);
// Combine the arrays into one...
return array_combine($keys, $values);
}
$myArray = shuffleAll($myArray);
$myArray should now have a custom assortment of your now non-matching key-value pairs. The original values have been preserved in $originalArray for latter processing and matching.
References:
array_combine(...)
array_keys(...)
array_values(...)
shuffle(...)
I am wondering how can I store all values from a foreach loop, I know that I am re-initialising in the loop but I'm not sure how to store the data. Heres my basic loop:
$array = array("v1", "v2", "v3", "v4");
foreach($array as $row){
$arr = array('val' => $row);
echo $row;
}
print_r($arr);
So when I use the print_r($arr) the only thing outputted would be v4 and I know that the values are there because the echo $row; does return each output individually.
My question would be how can I store each instance of row in my array?
Create a new array, fill it:
$array = array("v1", "v2", "v3", "v4");
$newArray = array();
foreach($array as $row){
// notice the brackets
$newArray[] = array('val' => $row);
}
print_r($newArray);
It looks like you are storing your array wrong.
Try adjusting the $arr = array('val' => $row);
to:
$arr[] = array('val' => $row);
This will set it so you pick up each line as a separate array which you can easily navigate through.
Hope this helps!
If I'm reading correctly, you want to transform your array from simple values to key-value pairs of 'val'->number. array_map is a concise way of doing this sort of transformation.
$array = array("v1", "v2", "v3", "v4");
$arr = array_map(function($v) { return array('val'=>$v); }, $array);
print_r($arr);
While it doesn't matter in this case, array_map also has the handy feature of preserving your keys, in case that is desired.
Note that you can also provide a named function to array_map, instead of providing the implementation inline, which can be nice in the event that your transform method gets more complicated. More on array_map here.
I have this kind of an array containing single-element arrays:
$array = [[88868], [88867], [88869], [88870]];
I need to convert this to one dimensional array.
Desired output:
[88868, 88867, 88869, 88870]
Is there any built-in/native PHP functionality for this array conversion?
For your limited use case, this'll do it:
$oneDimensionalArray = array_map('current', $twoDimensionalArray);
This can be more generalized for when the subarrays have many entries to this:
$oneDimensionalArray = call_user_func_array('array_merge', $twoDimensionalArray);
The PHP array_mergeĀDocs function can flatten your array:
$flat = call_user_func_array('array_merge', $array);
In case the original array has a higher depth than 2 levels, the SPL in PHP has a RecursiveArrayIterator you can use to flatten it:
$flat = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)), 0);
See as well: Turning multidimensional array into one-dimensional array
try:
$new_array = array();
foreach($big_array as $array)
{
foreach($array as $val)
{
array_push($new_array, $val);
}
}
print_r($new_array);
$oneDim = array();
foreach($twoDim as $i) {
$oneDim[] = $i[0];
}
Yup.
$values = array(array(88868), array(88867), array(88869), array(88870));
foreach ($values as &$value) $value = $value[0];
http://codepad.org/f9KjbCCb
foreach($array as $key => $value){
//check that $value is not empty and an array
if (!empty($value) && is_array($value)) {
foreach ($value as $k => $v) {
//pushing data to new array
$newArray[] = $v;
}
}
}
For a two dimensional array this works as well:
array_merge(...$twoDimensionalArray)
While some of the answers on the page that was previously used to close this page did have answers that suited this question (like array_merge(...$array)). There are techniques for this specific question that do not belong on the other page because of the input data structure.
The sample data structure here is an array of single-element, indexed arrays.
var_export(array_column($array, 0));
Is all that this question requires.
If you ever have a daft job interview that asks you to do it without any function calls, you can use a language construct (foreach()) and use "array destructuring" syntax to push values into a result variable without even writing a body for the loop. (Demo)
$result = [];
foreach ($array as [$result[]]);
var_export($result);
Laravel also has a flattening helper method: Arr::flatten()