multidimensional array with each to every connections - php

there is a multidimensional array like
[­["14","16"],["26"],["24"],["5","8"]]
the length of the total array is not limited, nested will be an average of 1-3 elements
nested ones will always be numbers, not arrays, i.e. the array is two-dimensional. the task is to get a "each with each" relationship, i.e. I should get sets of the kind
14,26,24,5;
14,26,24,8;
16,26,24,5;
16,26,24,8;
I tried cycles, and tried recursion, but it doesn’t work.
Can you help me please?
Thanks

$data = [
[2, 4],
[],
[3, 6],
[2, 3],
];
$output = array_reduce($data, function (array $carry = null, array $item = null): array {
if (!$carry) {
return $item;
}
if (!$item) {
return $carry;
}
$output = [];
foreach ($carry as $foo) {
foreach ($item as $bar) {
$output[] = $foo . '-' . $bar;
}
}
return $output;
});
print_r($output);
Output:
Array
(
[0] => 2-3-2
[1] => 2-3-3
[2] => 2-6-2
[3] => 2-6-3
[4] => 4-3-2
[5] => 4-3-3
[6] => 4-6-2
[7] => 4-6-3
)

Related

Convert Decimal-Number/MIB-Style Strings to Array Indices

I'm trying to convert mib-style strings into PHP array indices. The trick is that I have to do this for a variable number of strings. As an example:
$strings = ['1.1.1' => 1, '1.1.2' => 2, '1.2.1' => 1];
# Given the above, generate the below:
$array = [ 1 => [ 1 => [1 => 1, 2 => 2] ], 2 => [1 => 1] ] ] ] ]
I can't think of a way to do it that isn't just a brute-force, inefficient method. Any helpful function/approach/advice is welcome.
You could take a recursive approach since the problem/result you provide seems to be of a recursive nature. (You can achieve the same result with a loop, applying the same logic as the recursive function ofcourse)
So under the assumption that there are no conflicting string inputs/edge cases what so ever, the following could be one approach:
Loop over all the strings and their values, break it up and create a nested structure by passing the result array by its reference.
function createNested($pieces, $currentIndex, &$previous, $value)
{
$index = $pieces[$currentIndex];
// Our base case: when we reached the final/deepest level of nesting.
// Hence when the we reached the final index.
if ($currentIndex == count($pieces) - 1) {
// Can now safely assign the value to index.
$previous[$index] = $value;
} else {
// Have to make sure we do not override the key/index.
if (!key_exists($index, $previous)) {
$previous[$index] = [];
}
// If the key already existed we can just make a new recursive call (note one level deeper as we pass the array that $previous[$index] points to.
createNested($pieces, $currentIndex + 1, $previous[$index], $value);
}
}
$strings = ['1.1.1' => 1, '1.1.2' => 2, '1.2.1' => 1];
$result = [];
foreach ($strings as $string => $value) {
// Break up the string by .
createNested(explode('.', $string), 0, $result, $value);
}
echo '<pre>';
print_r($result);
echo '</pre>';
Will output:
Array
(
[1] => Array
(
[1] => Array
(
[1] => 1
[2] => 2
)
[2] => Array
(
[1] => 1
)
)
)

php making an assoc array in a for loop doesn't set the key [duplicate]

I've been looking on google for the answer but can't seem to find something fool-proof and cant really afford to mess this up (going live into a production site).
What I have is an advanced search with 20+ filters, which returns an array including an ID and a Distance. What I need to do is shuffle these results to display in a random order every time. The array I have that comes out at the moment is:
Array (
[0] => Array ( [id] => 1 [distance] => 1.95124994507577 )
[1] => Array ( [id] => 13 [distance] => 4.75358968511882 )
[2] => Array ( [id] => 7 [distance] => 33.2223233233323 )
[3] => Array ( [id] => 21 [distance] => 18.2155453552336 )
[4] => Array ( [id] => 102 [distance] = 221.2212587899658 )
)
What I need to be able to do is randomise or order of these every time but maintain the id and distance pairs, i.e.:
Array (
[4] => Array ( [id] => 102 [distance] = 221.2212587899658 )
[1] => Array ( [id] => 13 [distance] => 4.75358968511882 )
[3] => Array ( [id] => 21 [distance] => 18.2155453552336 )
[2] => Array ( [id] => 7 [distance] => 33.2223233233323 )
[0] => Array ( [id] => 1 [distance] => 1.95124994507577 )
)
Thanks :)
The first user post under the shuffle documentation:
Shuffle associative and
non-associative array while preserving
key, value pairs. Also returns the
shuffled array instead of shuffling it
in place.
function shuffle_assoc($list) {
if (!is_array($list)) return $list;
$keys = array_keys($list);
shuffle($keys);
$random = array();
foreach ($keys as $key) {
$random[$key] = $list[$key];
}
return $random;
}
Test case:
$arr = array();
$arr[] = array('id' => 5, 'foo' => 'hello');
$arr[] = array('id' => 7, 'foo' => 'byebye');
$arr[] = array('id' => 9, 'foo' => 'foo');
print_r(shuffle_assoc($arr));
print_r(shuffle_assoc($arr));
print_r(shuffle_assoc($arr));
As of 5.3.0 you could do:
uksort($array, function() { return rand() > rand(); });
Take a look to this function here :
$foo = array('A','B','C');
function shuffle_with_keys(&$array) {
/* Auxiliary array to hold the new order */
$aux = array();
/* We work with an array of the keys */
$keys = array_keys($array);
/* We shuffle the keys */`enter code here`
shuffle($keys);
/* We iterate thru' the new order of the keys */
foreach($keys as $key) {
/* We insert the key, value pair in its new order */
$aux[$key] = $array[$key];
/* We remove the element from the old array to save memory */
unset($array[$key]);
}
/* The auxiliary array with the new order overwrites the old variable */
$array = $aux;
}
shuffle_with_keys($foo);
var_dump($foo);
Original post here :
http://us3.php.net/manual/en/function.shuffle.php#83007
function shuffle_assoc($array)
{
$keys = array_keys($array);
shuffle($keys);
return array_merge(array_flip($keys), $array);
}
I was having a hard time with most of the answers provided - so I created this little snippet that took my arrays and randomized them while maintaining their keys:
function assoc_array_shuffle($array)
{
$orig = array_flip($array);
shuffle($array);
foreach($array AS $key=>$n)
{
$data[$n] = $orig[$n];
}
return array_flip($data);
}
Charles Iliya Krempeaux has a nice writeup on the issue and a function that worked really well for me:
function shuffle_assoc($array)
{
// Initialize
$shuffled_array = array();
// Get array's keys and shuffle them.
$shuffled_keys = array_keys($array);
shuffle($shuffled_keys);
// Create same array, but in shuffled order.
foreach ( $shuffled_keys AS $shuffled_key ) {
$shuffled_array[ $shuffled_key ] = $array[ $shuffled_key ];
} // foreach
// Return
return $shuffled_array;
}
Try using the fisher-yates algorithm from here:
function shuffle_me($shuffle_me) {
$randomized_keys = array_rand($shuffle_me, count($shuffle_me));
foreach($randomized_keys as $current_key) {
$shuffled_me[$current_key] = $shuffle_me[$current_key];
}
return $shuffled_me;
}
I had to implement something similar to this for my undergraduate senior thesis, and it works very well.
Answer using shuffle always return the same order. Here is one using random_int() where the order is different each time it is used:
function shuffle_assoc($array)
{
while (count($array)) {
$keys = array_keys($array);
$index = $keys[random_int(0, count($keys)-1)];
$array_rand[$index] = $array[$index];
unset($array[$index]);
}
return $array_rand;
}
$testArray = array('a' => 'apple', 'b' => 'ball', 'c' => 'cat', 'd' => 'dog');
$keys = array_keys($testArray); //Get the Keys of the array -> a, b, c, d
shuffle($keys); //Shuffle The keys array -> d, a, c, b
$shuffledArray = array();
foreach($keys as $key) {
$shuffledArray[$key] = $testArray[$key]; //Get the original array using keys from shuffled array
}
print_r($shuffledArray);
/*
Array
(
[d] => dog
[a] => apple
[c] => cat
[b] => ball
)
*/
I tried the most vote solution didn't popular shuffle list. This is the change I made to make it work.
I want my array key starting from 1.
$list = array_combine(range(1,10),range(100,110));
$shuffle_list = shuffle_assoc($list);
function shuffle_assoc($list)
{
if (!is_array($list)) return $list;
$keys = array_keys($list);
shuffle($list);
$random = array();
foreach ($keys as $k => $key) {
$random[$key] = $list[$k];
}
return $random;
}

Filter 2d array to keep all rows which contain a specific value

I have a two dimensional haystack array like this:
[
4 => [0, 1, 2, 3, 10],
1 => [0, 1, 2, 3, 10],
2 => [0, 1, 2, 3],
3 => [0, 1, 2, 3]
]
Let's say that I have a search value of $x = 10.
How can I search in above array and get an array index which contains $x.
In my current example, subarrays with key 4 and 1 contain value of $x -- I need those 2 subarrays.
You could loop then use array_search()
$array = array(...); // Your array
$x = 10;
foreach ($array as $key => $value) {
if (array_search($x, $value)) {
echo 'Found on Index ' . $key . '</br>';
}
}
Or if you need the arrays with those index
$array = array(...); // Your array
$x = 10;
$result = array(); // initialize results
foreach ($array as $key => $value) {
if (array_search($x, $value)) {
$result[] = $array[$key]; // push to result if found
}
}
print_r($result);
You can use array_filter() to keep only the array that contains the value you want:
$array = array(
array(0, 1, 2, 3, 10),
array(0, 1, 2, 3, 10),
array(0, 1, 2, 3),
array(0, 1, 2, 3)
);
$x = 10;
$out = array_filter($array, function($arr) use($x) {
return in_array($x, $arr);
});
print_r($out);
Output:
Array
(
[0] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 10
)
[1] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 10
)
)
You can use as well in_array
$array = array(); // Your array
$x = 10;
$result = array(); // initialize results
foreach ($array as $key => $value) {
if (in_array($x, $value)) {
$result[] = $array[$key]; //
}
}
print_r($result)
You can use array_search() function to search the value in array..
Link: http://php.net/manual/en/function.array-search.php
For Exp:
$x = 10; // search value
$array = array(...); // Your array
$result = array(); // Result array
foreach ($array as $key => $value)
{
if (array_search($x, $value))
{
$result[] = $array[$key]; // push the matched data into result array..
}
}
print_r($result);
You can use array_search();
doc: http://www.php.net/manual/en/function.array-search.php

Function to flatten a multidimensional array doesn't work as expected

All I am trying to do is flatten an arbitrary array of integers.
Here is my code:
<?php
$list_of_lists_of_lists = [[1, 2, [3]], [4, 3, 4, [5, 3, 4]], 3];
$flattened_list = [];
function flatten($l){
foreach ($l as $value) {
if (is_array($value)) {
flatten($value);
}else{
$flattened_list[] = $value;
}
}
}
flatten($list_of_lists_of_lists);
print_r($flattened_list);
?>
When I run this code, I get this:
Array ( )
I have no idea why. I did the exact same code in Python and it worked fine.
Can you guys point out, where I went wrong?
First you have a scope issue, that your result array is out of scope in the function. So just pass it as argument from call to call.
Second you also don't return your result array, which you have to do, if you want to use the result outside of the function.
Corrected code:
$list_of_lists_of_lists = [[1, 2, [3]], [4, 3, 4, [5, 3, 4]], 3];
function flatten($l, $flattened_list = []){
foreach ($l as $value) {
if(is_array($value)) {
$flattened_list = flatten($value, $flattened_list);
} else {
$flattened_list[] = $value;
}
}
return $flattened_list;
}
$flattened_list = flatten($list_of_lists_of_lists);
print_r($flattened_list);
output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 3
[5] => 4
[6] => 5
[7] => 3
[8] => 4
[9] => 3
)

PHP Random Shuffle Array Maintaining Key => Value

I've been looking on google for the answer but can't seem to find something fool-proof and cant really afford to mess this up (going live into a production site).
What I have is an advanced search with 20+ filters, which returns an array including an ID and a Distance. What I need to do is shuffle these results to display in a random order every time. The array I have that comes out at the moment is:
Array (
[0] => Array ( [id] => 1 [distance] => 1.95124994507577 )
[1] => Array ( [id] => 13 [distance] => 4.75358968511882 )
[2] => Array ( [id] => 7 [distance] => 33.2223233233323 )
[3] => Array ( [id] => 21 [distance] => 18.2155453552336 )
[4] => Array ( [id] => 102 [distance] = 221.2212587899658 )
)
What I need to be able to do is randomise or order of these every time but maintain the id and distance pairs, i.e.:
Array (
[4] => Array ( [id] => 102 [distance] = 221.2212587899658 )
[1] => Array ( [id] => 13 [distance] => 4.75358968511882 )
[3] => Array ( [id] => 21 [distance] => 18.2155453552336 )
[2] => Array ( [id] => 7 [distance] => 33.2223233233323 )
[0] => Array ( [id] => 1 [distance] => 1.95124994507577 )
)
Thanks :)
The first user post under the shuffle documentation:
Shuffle associative and
non-associative array while preserving
key, value pairs. Also returns the
shuffled array instead of shuffling it
in place.
function shuffle_assoc($list) {
if (!is_array($list)) return $list;
$keys = array_keys($list);
shuffle($keys);
$random = array();
foreach ($keys as $key) {
$random[$key] = $list[$key];
}
return $random;
}
Test case:
$arr = array();
$arr[] = array('id' => 5, 'foo' => 'hello');
$arr[] = array('id' => 7, 'foo' => 'byebye');
$arr[] = array('id' => 9, 'foo' => 'foo');
print_r(shuffle_assoc($arr));
print_r(shuffle_assoc($arr));
print_r(shuffle_assoc($arr));
As of 5.3.0 you could do:
uksort($array, function() { return rand() > rand(); });
Take a look to this function here :
$foo = array('A','B','C');
function shuffle_with_keys(&$array) {
/* Auxiliary array to hold the new order */
$aux = array();
/* We work with an array of the keys */
$keys = array_keys($array);
/* We shuffle the keys */`enter code here`
shuffle($keys);
/* We iterate thru' the new order of the keys */
foreach($keys as $key) {
/* We insert the key, value pair in its new order */
$aux[$key] = $array[$key];
/* We remove the element from the old array to save memory */
unset($array[$key]);
}
/* The auxiliary array with the new order overwrites the old variable */
$array = $aux;
}
shuffle_with_keys($foo);
var_dump($foo);
Original post here :
http://us3.php.net/manual/en/function.shuffle.php#83007
function shuffle_assoc($array)
{
$keys = array_keys($array);
shuffle($keys);
return array_merge(array_flip($keys), $array);
}
I was having a hard time with most of the answers provided - so I created this little snippet that took my arrays and randomized them while maintaining their keys:
function assoc_array_shuffle($array)
{
$orig = array_flip($array);
shuffle($array);
foreach($array AS $key=>$n)
{
$data[$n] = $orig[$n];
}
return array_flip($data);
}
Charles Iliya Krempeaux has a nice writeup on the issue and a function that worked really well for me:
function shuffle_assoc($array)
{
// Initialize
$shuffled_array = array();
// Get array's keys and shuffle them.
$shuffled_keys = array_keys($array);
shuffle($shuffled_keys);
// Create same array, but in shuffled order.
foreach ( $shuffled_keys AS $shuffled_key ) {
$shuffled_array[ $shuffled_key ] = $array[ $shuffled_key ];
} // foreach
// Return
return $shuffled_array;
}
Try using the fisher-yates algorithm from here:
function shuffle_me($shuffle_me) {
$randomized_keys = array_rand($shuffle_me, count($shuffle_me));
foreach($randomized_keys as $current_key) {
$shuffled_me[$current_key] = $shuffle_me[$current_key];
}
return $shuffled_me;
}
I had to implement something similar to this for my undergraduate senior thesis, and it works very well.
Answer using shuffle always return the same order. Here is one using random_int() where the order is different each time it is used:
function shuffle_assoc($array)
{
while (count($array)) {
$keys = array_keys($array);
$index = $keys[random_int(0, count($keys)-1)];
$array_rand[$index] = $array[$index];
unset($array[$index]);
}
return $array_rand;
}
$testArray = array('a' => 'apple', 'b' => 'ball', 'c' => 'cat', 'd' => 'dog');
$keys = array_keys($testArray); //Get the Keys of the array -> a, b, c, d
shuffle($keys); //Shuffle The keys array -> d, a, c, b
$shuffledArray = array();
foreach($keys as $key) {
$shuffledArray[$key] = $testArray[$key]; //Get the original array using keys from shuffled array
}
print_r($shuffledArray);
/*
Array
(
[d] => dog
[a] => apple
[c] => cat
[b] => ball
)
*/
I tried the most vote solution didn't popular shuffle list. This is the change I made to make it work.
I want my array key starting from 1.
$list = array_combine(range(1,10),range(100,110));
$shuffle_list = shuffle_assoc($list);
function shuffle_assoc($list)
{
if (!is_array($list)) return $list;
$keys = array_keys($list);
shuffle($list);
$random = array();
foreach ($keys as $k => $key) {
$random[$key] = $list[$k];
}
return $random;
}

Categories