multi dimensional array in random order - php

I want to make it so that my multi dimensional array is in a random order. How would you do it?
// This is how the array looks like
print_r($slides);
Array
(
[0] => Array
(
[id] => 7
[status] => 1
[sortorder] => 0
[title] => Pants
)
[1] => Array
(
[id] => 8
[status] => 1
[sortorder] => 0
[title] => Jewels
)
[2] => Array
(
[id] => 9
[status] => 1
[sortorder] => 0
[title] => Birdhouse
)
[3] => Array
(
[id] => 10
[status] => 1
[sortorder] => 0
[title] => Shirt
)
[4] => Array
(
[id] => 11
[status] => 1
[sortorder] => 0
[title] => Phone
)
)
// This how the result is if I use array_rand()
print_r(array_rand($slides, 5));
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
)
// This how the result is if I use shuffle()
print_r(shuffle($slides));
1

shuffle() is the way to go here. It prints 1 because shuffle changes the array in-place and returns a boolean, as it is written in the documentation:
Returns TRUE on success or FALSE on failure.
I suggest to also read the documentation of array_rand():
Picks one or more random entries out of an array, and returns the key (or keys) of the random entries.
Always read documentation if you use built-in functions. Don't just assume how the work. I bet it took more time to write the question than looking this up.

Instead of
print_r(shuffle($slides));
do
shuffle($slides);
print_r($slides);
You see shuffle() shuffles the array in-place

i am not sure how you want it to display but you can loop the array and use php rand(0,arraylen) function to parse the array.

It works perfect. print_r(shuffle($slides))) gives the output of TRUE, since the return value of shuffle is a boolean and not an array.
See the working example here: http://codepad.org/B5SlcjGf

Related

in_array() not working with two dimensional associative array?

I'm trying very simply to use in_array() to check a key is in an array and then echo its value.
$array = Array
(
[cart_item] => Array
(
[0] => Array
(
[product_name] => White Sakura Necktie
[id] => 11
[product_auto_id] => 556729685
[quantity] => 2
[product_regular_price] => 95
[product_sale_price] => 95
[product_image] => 556729680Black_Sakura_Necktie.jpg
)
[1] => Array
(
[product_name] => hhhad ba bhdbh
[id] => 10
[product_auto_id] => 951790801
[quantity] => 2
[product_regular_price] => 20
[product_sale_price] =>
[product_image] => 951790801hhhad_ba_bhdbh_.jpg
)
)
)
And I have value 556729685 which I want to check that this value exists or not? So I am using in_array() function for this.
in_array(556729685, array_keys($array));
in_array(556729685, array_values($array));
in_array(556729685, $array);
All above three i have used but result always showing NULL means blank.
I am really frustrated to find the solution. I don't understand what's happening.
You should use array_column() which will return the values from a single column in the input array as an array.
$product_auto_ids = array_column($array['cart_item'], 'product_auto_id');
In this case, it would return the following:
Array
(
[0] => 556729685
[1] => 951790801
)
Then you can use in_array() like you currently are.
in_array(556729685, $product_auto_ids);

finding the lowest value integer from data stored in an array using php

I have an array called $quotes and when I print_r an example of the results are like this:
Array ( [id] => advshipper [methods] => Array (
[0] => Array ( [id] => 2-0-0 [title] => Small Parcels [cost] => 4.5 [icon] => [shipping_ts] => [quote_i] => 0 )
[1] => Array ( [id] => 3-0-0 [title] => Large Parcels up to 1150mm long [cost] => 8.95 [icon] => [shipping_ts] => [quote_i] => 1 )
[2] => Array ( [id] => 4-0-0 [title] => Extra Large Parcels over 1150mm long [cost] => 15 [icon] => [shipping_ts] => [quote_i] => 2 ) ) [module] => Shipping )
What I need is a simple way to look at $quotes, find which [cost] has the lowest value and then record, in this example, the [0] so that they can be used in another code segment.
Short of exploding the array and then looping through all the content, is there a simple method to achieve what I want?
As you are using the version higher than 5.5, you can simply use array_column function:
echo min(array_column($quotes['id'],'cost'));
And if you want, you can retrieve the id of the row as well:
echo min(array_column($quotes['id'], 'cost', 'id'));
array_reduce($quotes, function($minimum, $current) {
return $current['cost'] < $minimum['cost'] ? $current : $minimum;
}, $quotes[0]);
This will return the row of $quotes that has the lowest value of cost.
If I understood that correctly, you need to find the lowest value for cost array.
You can do an array_map to get the values
$lowestcost = array_map(function($costval) {
return $costval['cost'];
}, $array);
Then you need to use
min($lowestcost)
Hope this helps

php access array by key value

I have a JSON array which Im trying to parse with PHP using array_column (PHP 5.5).
My objective is to check the value of a particular key in the array and execute some additional code dependent on the result.
For example with the array below...I would like to find field_number 335 in the array and take the value (Last name) and echo to the screen. The actual array [1] could be different each time as the array grows, where as field_number would always be 335.
Array
(
[0] => Array
(
[id] => 286
[lead_id] => 5
[form_id] => 4
[field_number] => 1
[value] => First Name
)
[1] => Array
(
[id] => 287
[lead_id] => 5
[form_id] => 4
[field_number] => 335
[value] => Last name
)
[2] => Array
(
[id] => 288
[lead_id] => 5
[form_id] => 4
[field_number] => 339
[value] => Australia
)
Hopefully that makes sense and with enough information to help someone point me in the right direction.
Many thanks all!
Cheers
you can use array_search && array_column
$key = array_search('335', array_column($array, 'field_number'));
this should give you array id
eg. echo $array[$key]['value'];

PHP Group by value and sort randomly

I want to group an associative array by value and randomize the items per group.
I have the following array $result
Aray(
[0] => Building Object
(
[id] => 285
[formula] => 4
[title] => test 1
)
[1] => Building Object
(
[id] => 120
[formula] => 4
[title] => test 2
)
[2] => Building Object
(
[id] => 199
[formula] => 2
[title] => test 3
)
[3] => Building Object
(
[id] => 231
[formula] => 1
[title] => test 4
)
[3] => Building Object
(
[id] => 230
[formula] => 1
[title] => test 5
)
)
So I want to group the array by its formula so the objects with formula 4 should be on top. But the buildings should be per group random so first id 285 on top then id 120 on top... So I want randomly
Aray(
[0] => Building Object
(
[id] => 285
[formula] => 4
[title] => test 1
)
[1] => Building Object
(
[id] => 120
[formula] => 4
[title] => test 2
) ..
How can I do this I tried:
shulffle($result);
usort($result, "cmp");
But that doesn't keep my array grouped by the formula.
usort is the right function, but you need to be more specific:
// drop the `shuffle`, we'll be shuffling in the sort
usort($result,function($a,$b) {
// PHP 5.4 or newer:
return ($a->formula - $b->formula) ?: rand(-1,1);
// older PHP:
if( $a->formula == $b->formula) return rand(-1,1);
return $a->formula - $b->formula;
});
And before people say my shuffling "isn't really random", I say "it's random enough for this application".

Issue getting info out of array

I'm trying to get info out of this information:
Array (
[result] => success
[totalresults] => 1
[startnumber] => 0
[numreturned] => 1
[tickets] => Array (
[ticket] => Array (
[0] => Array (
[id] => 7
[tid] => 782755
[deptid] => 1
[userid] => 39
[name] => Mark Lønquist
[email] => mark.loenquist#outlook.com
[cc] =>
[c] => 79rzVBeJ
[date] => 2013-04-25 16:14:24
[subject] => test
[status] => Open
[priority] => Medium
[admin] =>
[attachment] =>
[lastreply] => 2013-04-25 16:14:24
[flag] => 0
[service] =>
)
)
)
)
The results are printed using:
print_r($results);
Usually, I've been able to do a simple:
$var = $results['something'];
To get it out, but it wont work with this :( Any help is appreciated.
After reformatting the array you pasted, it becomes clear that some elements are nested several levels deep. (It's a "multidimensional array"; see example #6 in the docs.) In those cases, you have to add additional brackets containing each successive key to reach the depth you want. For example, a sample from your $results array:
Array (
[result] => success
[totalresults] => 1
...
[tickets] => Array (
[ticket] => Array (
[0] => Array (
[id] => 7
[tid] => 782755
...
)
)
)
)
You simply need to do $results['totalresults'] to access "totalresults", but to get "tid" you would need to use $results['tickets']['ticket'][0]['tid'].
If you want to get "tid" from all of the tickets when there are multiple, you will have to iterate (loop) over the array of tickets. Probably something like this (untested, but should be close enough for you to figure out):
foreach ($results['tickets']['ticket'] as $ticket) {
echo $ticket['tid'];
}
To see what the problem is with your print_r() you may add error_reporting(E_ALL); to the top of your code.
Note that if you want to retrieve the value for a key such as 'totalresults' then $results['totalresults'] would be sufficient.
However, if you want to get a key from one of the nested arrays such as email then you would have to use $results['result']['tickets']['ticket'][0]['email'].

Categories