I'm having trouble correctly iterating a multi-dimension array I am trying to retrieve the values for each well..value.
My Issue is I seem to have an array within an array which has an array for each key/pair value, I'm unsure how to loop through these and add the values to the database for each array.
Eg, if I have one form on my page the array return is below and further below that is what is returned with two forms etc
Array
(
[0] => Array
(
[0] => Array
(
[name] => sl_propid
[value] => 21
)
[1] => Array
(
[name] => sl_date
[value] => 04/01/2014
)
[2] => Array
(
[name] => sl_ref
[value] => Form1
)
[3] => Array
(
[name] => sl_nom_id
[value] => 12
)
[4] => Array
(
[name] => sl_desc
[value] => Form1
)
[5] => Array
(
[name] => sl_vat
[value] => 60
)
[6] => Array
(
[name] => sl_net
[value] => 999
)
)
)
My question is how do I iterate through the returned array no matter it's size and pull back each value?
I have tried nesting foreach loops, which did give me results, but only for one key/value pair which leads me to believe I'm doing the looping wrong, I can retrieve the values if I statically access them, which is of course no use normally.
foreach ($result as $array) {
print_r($array);
}
the above foreach returns the above arrays, adding another foreach removes the out "container" array but adding another foreach loop, returns only one key/value pair, which sort makes sense because the first index is an array, too, hope I haven't confused everyone else as much as already have myself D:.
Thank you for reading
Any help appreciated.
EDIT Using the below array walk recursive I get the output
$result = $this->input->post();
function test_print($item, $key)
{
echo "$key holds $item\n";
//$this->SalesLedgerModel->addInvoiceToLedger($key, $key, $key, $key, $key, $key, $key);
}
array_walk_recursive($result, 'test_print');
}
Which is almost what I want but how do I take each individual value and add it to my ModelFunction (to actually input the data to DB)
The function takes 7 parameters but I am unsure how to make sure the right info goes to the correct parameter
$this->SalesLedgerModel->addInvoiceToLedger($propid, $date, $ref, $nomid, $desc, $vat, $net);
My Controller function
function addInvoiceToLedger(){
$this->load->model('SalesLedgerModel');
// $propid = $this->input->post('propid');
// $date = $this->input->post('date');
// $ref = $this->input->post('ref');
// $nomid = $this->input->post('id');
// $desc = $this->input->post('desc');
// $vat = $this->input->post('vat');
// $net = $this->input->post('sl_net');
$results = $this->input->post();
//var_dump($results);
$size1 = sizeof($results)-1;
for($i=0; $i<=$size1; $i++)
{
$size2 = sizeof($results[$i])-1;
for($j=0; $j<=$size2; $j++)
{
$name = $results[$i][$j]['name'];
$value = $results[$i][$j]['value'];
echo $value . "\n" ;
$this->SalesLedgerModel->addInvoiceToLedger($value, $value, $value, $value, $value, $value, $value);
}
}
My Model function
function addInvoiceToLedger($propid, $date, $ref, $nomid, $desc, $vat, $net){
$data = array('sl_prop_id' => $propid, 'sl_date' => $date,
'sl_ref' => $ref, 'sl_nominal_sub' => $nomid, 'sl_invoice_desc' => $desc, 'sl_vat' => $vat, 'sl_amount' => $net);
$this->db->insert('salesledger', $data);
}
You can either write some recursive code to step through the array and call itself again if an element turns into an array, or write a very simple function and call it via array walk recursive which will then let you do whatever you like with the value:
<?php
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');
function test_print($item, $key)
{
echo "$key holds $item\n";
}
array_walk_recursive($fruits, 'test_print');
?>
Output:
a holds apple
b holds banana
sour holds lemon
Try this. It'll be much faster. Since 3 foreach loops is much costlier than 2 for loops (for loops are faster than foreach loops) -
$size1 = sizeof($results)-1;
if($size1 > 0)
{
for($i=0; $i<=$size1; $i++)
{
$size2 = sizeof($results[$i])-1;
if($size2 > 0)
{
for($j=0; $j<=$size2; $j++)
{
$name = $results[$i][$j]['name'];
$value = $results[$i][$j]['value'];
$insert = $this->your_model->insert($name, $value);
}
}
}
}
foreach ($result as $array) {
foreach($array as $arr){
foreach($arr as $a){
echo $a[value];
}
}
}
Related
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;
}
For the building of a url query I need to combine one value(key) of an array to all the values(value) of another array. Each combined key => value needs to be added to an array.
The problem here is that I can combine the values of the two arrays in two foreach statements, but it creates for every instance a new array.
Update
Having duplicates is impossible so mine initial output is correct.
$array1 array(
[0] => music
[1] => product
)
$array2 array(
[0] => '));waitfor delay '0:0:TIME'--1
[1] => '[TAB]or[TAB]sleep(TIME)='
)
public static function create_combined_array($array1, $array2)
{
$newArray = array();
foreach ($array1 as $key){
//key = [music]
foreach ($array2 as $value) {
//one of the values is = '));waitfor delay '0:0:__TIME__'--1
array_push($newArray, [$key => $value]);
}
}
return $newArray;
}
Implementation
$query_array = Utils::create_combined_array($params, $payload_lines);
print_r($query_array);
$query = http_build_query($query_array);
$this->url = $baseUrl . '?' . $query;
Build query output
protocol://localhost:8000?music='));waitfor delay '0:0:TIME'--1
Sample output
[54] => Array
(
[music] => ));waitfor delay '0:0:__TIME__'--[LF]1
)
[55] => Array
(
[music] => '));waitfor delay '0:0:__TIME__'--1
)
[56] => Array
(
[music] => '));waitfor delay '0:0:__TIME__'--[LF]1
)
[57] => Array
(
[music] => "));waitfor delay '0:0:__TIME__'--1
)
What I wanted to achieve is impossible in PHP.
Example duplicates
Array(
[music] => "));waitfor delay '0:0:__TIME__'--1
[music] => '/**/or/**/benchmark(10000000,MD5(1))#1
)
Use code below:
public static function create_combined_array($array1, $array2)
{
$newArray = array();
foreach ($array1 as $key){
foreach ($array2 as $i => $value) {
$newArray[$i][$key] = $value;
}
}
return $newArray;
}
The key line is $newArray[$i][$key] = $value;. It appends an array to the $newArray at $i index which is the index of your second array $array2.
I am having a terrible time getting this to work I have been struggling with it for a couple hours now. Can someone please help me? I have included a fiddle.
I believe my problem is in this string:
$$salesAndOwner[$i]["$salesAndOwner[$i]".$l] = $salesAndOwner[$i.$l][$param] = $values[$l];
Basically I have the following multidimensional array:
[sales] => Array
(
[FirstName] => Array
(
[0] => salesFirst1
[1] => salesFirst2
)
[LastName] => Array
(
[0] => salesLast1
[1] => salesLast2
)
)
[decisionmaker] => Array
(
[FirstName] => Array
(
[0] => dmFirst1
[1] => dmFirst2
)
[LastName] => Array
(
[0] => dmLast1
[1] => dmLast2
)
)
)
I need this to be reorganized like I did with the following array:
Array
(
[additionallocations0] => Array
(
[Address] => Address1
[State] => State1
)
[additionallocations1] => Array
(
[Address] => Address2
[State] => State2
)
)
Here is the original:
Array
(
[additionallocations] => Array
(
[Address] => Array
(
[0] => Address1
[1] => Address2
)
[State] => Array
(
[0] => State1
[1] => State2
)
)
This is how I reorganize the above array:
if(isset($_POST['additionallocations'])) {
$qty = count($_POST['additionallocations']["Address"]);
for ($l=0; $l<$qty; $l++)
{
foreach($_POST['additionallocations'] as $param => $values)
{
$additional['additionallocations'.$l][$param] = $values[$l];
}
}
And this is what I am using for the sales and decisionmaker array. If you notice I have an array that contains sales and decisionmaker in it. I would like to be able to sort any future arrays by just adding its primary arrays name. I feel I am close to solving my problem but I can not get it to produce right.
$salesAndOwner = array(0 => "sales", 1 => "decisionmaker");
for($i = 0; $i < 2; $i++){
$qty = count($_POST[$salesAndOwner[$i]]["FirstName"]);
for ($l=0; $l<$qty; $l++)
{
foreach($_POST[$salesAndOwner[$i]] as $param => $values)
{
$$salesAndOwner[$i]["$salesAndOwner[$i]".$l] = $salesAndOwner[$i.$l][$param] = $values[$l];
}
}
}
In the above code I hard coded 'sales' into the variable I need it to make a variable name dynamically that contains the sales0 decisionmaker0 and sales1 decisionmaker1 arrays so $sales and $decisionmaker
I hope this makes sense please let me know if you need any more info
Let's break it down. Using friendly variable names and spacing will make your code a lot easier to read.
Remember. The syntax is for you to read and understand easily. (Not even just you, but maybe future developers after you!)
So you have an array of groups. Each group contains an array of attributes. Each attribute row contains a number of attribute values.
PHP's foreach is a fantastic way to iterate through this, because you will need to iterate through (and use) the index names of the arrays:
<?php
$new_array = array();
// For each group:
foreach($original_array as $group_name => $group) {
// $group_name = e.g 'sales'
// For each attribute in this group:
foreach($group as $attribute_name => $attributes) {
// $attribute_name = e.g. 'FirstName'
// For each attribute value in this attribute set.
foreach($attributes as $row_number => $attribute) {
// E.g. sales0
$row_key = $group_name . $row_number;
// if this is the first iteration, we need to declare the array.
if(!isset($new_array[$row_key])) {
$new_array[$row_key] = array();
}
// e.g. Array[sales0][FirstName]
$new_array[$row_key][$attribute_name] = $attribute;
}
}
}
?>
With this said, this sort of conversion may cause unexpected results without sufficient validation.
Make sure the input array is valid (e.g. each attribute group has the same number of rows per group) and you should be okay.
$salesAndOwner = array("sales", "decisionmaker");
$result = array();
foreach ($salesAndOwner as $key) {
$group = $_POST[$key];
$subkeys = array_keys($group);
$first_key = $subkeys[0];
foreach ($group[$first_key] as $i => $val) {
$prefix = $key . $i;
foreach ($subkeys as $subkey) {
if (!isset($result[$prefix])) {
$result[$prefix] = array();
}
$result[$prefix][$subkey] = $val;
}
}
}
DEMO
Try
$result =array();
foreach($arr as $key=>$val){
foreach($val as $key1=>$val1){
foreach($val1 as $key2=>$val2){
$result[$key.$key2][$key1] = $val2;
}
}
}
See demo here
I have two multidimensional arrays. First one $properties contains english names and their values. My second array contains the translations. An example
$properties[] = array(array("Floor"=>"5qm"));
$properties[] = array(array("Height"=>"10m"));
$translations[] = array(array("Floor"=>"Boden"));
$translations[] = array(array("Height"=>"Höhe"));
(They are multidimensional because the contains more elements, but they shouldn't matter now)
Now I want to translate this Array, so that I its at the end like this:
$properties[] = array(array("Boden"=>"5qm"));
$properties[] = array(array("Höhe"=>"10m"));
I have managed to build the foreach construct to loop through these arrays, but at the end it is not translated, the problem is, how I tell the array to replace the key with the value.
What I have done is this:
//Translate Array
foreach ($properties as $PropertyArray) {
//need second foreach because multidimensional array
foreach ($PropertyArray as $P_KiviPropertyNameKey => $P_PropertyValue) {
foreach ($translations as $TranslationArray) {
//same as above
foreach ($TranslationArray as $T_KiviTranslationPropertyKey => $T_KiviTranslationValue) {
if ($P_KiviPropertyNameKey == $T_KiviTranslationPropertyKey) {
//Name found, save new array key
$P_KiviPropertyNameKey = $T_KiviTranslationValue;
}
}
}
}
}
The problem is with the line where to save the new key:
$P_KiviPropertyNameKey = $T_KiviTranslationValue;
I know this part is executed correctly and contains the correct variables, but I believe this is the false way to assing the new key.
This is the way it should be done:
$properties[$oldkey] = $translations[$newkey];
So I tried this one:
$PropertyArray[$P_KiviPropertyNameKey] = $TranslationArray[$T_KiviTranslationPropertyKey];
As far as I understood, the above line should change the P_KiviPropertyNameKey of the PropertyArray into the value of Translation Array but I do not receive any error nor is the name translated. How should this be done correctly?
Thank you for any help!
Additional info
This is a live example of the properties array
Array
(
[0] => Array
(
[country_id] => 4402
)
[1] => Array
(
[iv_person_phone] => 03-11
)
[2] => Array
(
[companyperson_lastname] => Kallio
)
[3] => Array
(
[rc_lot_area_m2] => 2412.7
)
[56] => Array
(
[floors] => 3
)
[57] => Array
(
[total_area_m2] => 97.0
)
[58] => Array
(
[igglo_silentsale_realty_flag] => false
)
[59] => Array
(
[possession_partition_flag] => false
)
[60] => Array
(
[charges_parkingspace] => 10
)
[61] => Array
(
[0] => Array
(
[image_realtyimagetype_id] => yleiskuva
)
[1] => Array
(
[image_itemimagetype_name] => kivirealty-original
)
[2] => Array
(
[image_desc] => makuuhuone
)
)
)
And this is a live example of the translations array
Array
(
[0] => Array
(
[addr_region_area_id] => Maakunta
[group] => Kohde
)
[1] => Array
(
[addr_town_area] => Kunta
[group] => Kohde
)
[2] => Array
(
[arable_no_flag] => Ei peltoa
[group] => Kohde
)
[3] => Array
(
[arableland] => Pellon kuvaus
[group] => Kohde
)
)
I can build the translations array in another way. I did this like this, because in the second step I have to check, which group the keys belong to...
Try this :
$properties = array();
$translations = array();
$properties[] = array("Floor"=>"5qm");
$properties[] = array("Height"=>"10m");
$translations[] = array("Floor"=>"Boden");
$translations[] = array("Height"=>"Höhe");
$temp = call_user_func_array('array_merge_recursive', $translations);
$result = array();
foreach($properties as $key=>$val){
foreach($val as $k=>$v){
$result[$key][$temp[$k]] = $v;
}
}
echo "<pre>";
print_r($result);
output:
Array
(
[0] => Array
(
[Boden] => 5qm
)
[1] => Array
(
[Höhe] => 10m
)
)
Please note : I changed the array to $properties[] = array("Floor"=>"5qm");, Removed a level of array, I guess this is how you need to structure your array.
According to the structure of $properties and $translations, you somehow know how these are connected. It's a bit vague how the indices of the array match eachother, meaning the values in $properties at index 0 is the equivalent for the translation in $translations at index 0.
I'm just wondering why the $translations array need to have the same structure (in nesting) as the $properties array. To my opinion the word Height can only mean Höhe in German. Representing it as an array would suggest there are multiple translations possible.
So if you could narrow down the $translations array to an one dimensional array as in:
$translation = array(
"Height"=>"Höhe",
"Floor"=>"Boden"
);
A possible loop would be
$result = array();
foreach($properties as $i => $array2) {
foreach($array2 as $i2 => $array3) {
foreach($array3 as $key => $value) {
$translatedKey = array_key_exists($key, $translations) ?
$translations[$key]:
$key;
$result[$i][$i2][$translatedKey] = $value;
}
}
}
(I see every body posting 2 loops, it's an array,array,array structure, not array,array ..)
If you cannot narrow down the translation array to a one dimensional array, then I'm just wondering if each index in the $properties array matches the same index in the $translations array, if so it's the same trick by adding the indices (location):
$translatedKey = $translations[$i][$i2][$key];
I've used array_key_exists because I'm not sure a translation key is always present. You have to create the logic for each case scenario yourself on what to check or not.
This is a fully recursive way to do it.
/* input */
$properties[] = array(array("Floor"=>"5qm", array("Test"=>"123")));
$properties[] = array(array("Height"=>"10m"));
$translations[] = array(array("Floor"=>"Boden", array("Test"=>"Foo")));
$translations[] = array(array("Height"=>"Höhe"));
function array_flip_recursive($arr) {
foreach ($arr as $key => $val) {
if (is_array($val)) {
$arr[$key] = array_flip_recursive($val);
}
else {
$arr = #array_flip($arr);
}
}
return $arr;
}
function array_merge_it($arr) {
foreach ($arr as $key => $val) {
if (is_array($val)) {
$arr[$key] = array_merge_it($val);
} else {
if(isset($arr[$key]) && !empty($arr[$key])) {
#$arr[$key] = $arr[$val];
}
}
}
return $arr;
}
function array_delete_empty($arr) {
foreach ($arr as $key => $val) {
if (is_array($val)) {
$arr[$key] = array_delete_empty($val);
}
else {
if(empty($arr[$key])) {
unset($arr[$key]);
}
}
}
return $arr;
}
$arr = array_replace_recursive($properties, $translations);
$arr = array_flip_recursive($arr);
$arr = array_replace_recursive($arr, $properties);
$arr = array_merge_it($arr);
$arr = array_delete_empty($arr);
print_r($arr);
http://sandbox.onlinephpfunctions.com/code/d2f92605b609b9739964ece9a4d8f389be4a7b81
You have to do the for loop in this way. If i understood you right (i.e) in associative array first key is same (some index).
foreach($properties as $key => $values) {
foreach($values as $key1 => $value1) {
$propertyResult[] = array($translations[$key][$key1][$value1] => $properties[$key][$key1][$value1]);
}
}
print_r($propertyResult);
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;
}