I have the following PHP multidimensional array, I'm looking to try select 4 random items and then show them with the title, image and text. With the code I've used I seem to get a single number which is randomized and not what I need.
<?php
$arr = array(
array(
"image" => "",
"title" => "Open 7 days.",
"text" => "We’re open 7 days a week."
),
array(
"image" => "",
"title" => "Well done",
"text" => "Well done you done great."
),
array(
"image" => "",
"title" => "Rice",
"text" => "Various flavours"
),
array(
"image" => "",
"title" => "Rooms",
"text" => "Roomy rooms for a roomyful time"
),
array(
"image" => "",
"title" => "Keep in touch.",
"text" => "Stay in touchwith us as we'll miss you"
),
array(
"image" => "",
"title" => "Location",
"text" => "We'll show you where we are."
),
array(
"image" => "",
"title" => "The Home",
"text" => "See our home page"
)
);
print_r(array_rand($arr));
If you're picking only one entry, array_rand() returns a single key for a random entry. If you use the num to specify how many keys should be picked, then it returns num number of keys of random entries.
The function only returns the keys of the random entries and not the array chunks itself. You'll have to manually build the array from the returned keys:
// get the random keys
$keys = array_rand($arr, 4);
// initialize result array
$result = array();
// loop through the keys and build the array
foreach ($keys as $k) {
$result[] = $arr[$k];
}
print_r($result);
Update
From a quick benchmark, it seems array_rand() is signficantly faster than using shuffle() for larger arrays. The benchmark was done on an array having 14336 elements with 10000 iterations each.
The results obtained on my dev machine were as follows:
Number of elements in the array - 14336
Number of iterations for each method - 10000
array_rand() version took 4.659 seconds
shuffle() version took 15.071 seconds
The code used for benchmarking can be found in this gist.
No need to loop !
shuffle() and array_slice() does the job.
Simply shuffle your array such that it rearranges the entries , now pick the first 4 items using array_slice.
shuffle($arr);
print_r(array_slice($arr,0,4));
Demo
Read about the $num parameter array_rand()
print_r(array_rand($arr, 4));
To display all:
foreach(array_rand($arr, 4) as $key) {
echo $arr[$key]['text'] ."\n";
//etc
}
Related
I have an array of numbers that I need to search through a multidimensional array for.
I have a thousand records of songs. Each song has an array of float values that I need to search through, and I'll need to retrieve the songs if the first digits of each float value match any float number in my array.
So for example my array of numbers I need to find are:
array(14, 18.12, 12.1290, 55.01)
and the songs are sorted in a json file like so:
{"id": 129112, "name": "XYZ Song", "values": { 14.1290, 55.0192, 129 } }
Currently my for loops are taking too long to loop through all the records.
I think I need to sort through the values with a preg_match function and the right pattern (except I'm terrible with regex), what do you guys think?
Please check this code. This code may help you
<?php
// PHP program to carry out multidimensional array search
// Function to recursively search for a given value
function multi_array_search($search_value, $array, $id_path) {
if(is_array($array) && count($array) > 0) {
foreach($array as $key => $value) {
$temp_path = $id_path;
// Adding current key to search path
$temp_path[] = $value;
// Check if this value is an array
// with atleast one element
if(is_array($value) && count($value) > 0) {
$res_path = multi_array_search(
$search_value, $value, $temp_path);
}
else if($value == $search_value) {
print_r($temp_path);
}
}
}
}
// Multidimensional (Three dimensional) array as suggested by you
$songs_array= array(
0 => array(
"id" => "129112",
"name" => "X Song",
"value" => array( 14.1290, 329, 129 )
),
1 => array(
"id" => "129113",
"name" => "XY Song",
"value" => array( 14.1291, 55.0192, 229 )
),
2 => array(
"ic" => "129114",
"name" => "XYZ Song",
"value" => array( 14.1292, 55.0193, 388 )
)
);
$songs= multi_array_search('329', $songs_array, array());
?>
Here I have searched for 329 in $song_array and
Result is :
I have a query which returns several thousands objects from my database. The result set is an array of associative arrays. An example would be something along the lines of:
Array(
Array(
"id" => 500,
"name" => "Bob"
),
Array(
"id" => 2,
"name" => "Cindy"
),
Array(
"id" => 200,
"name" => "Jane"
)
);
In this case I'd need to be able to filter/sort this array to retrieve the id of 500.
Here's one way to do it:
Get the ids into an array (using array_column())
Get the highest value in the array (using max())
This should do the trick:
echo max(array_column($array, 'id'));
Demo
I'm trying to learn some basic PHP but am running into some confusion around using arrays.
I have three "pools" of words. 20 words in each pool for a total of 60 words.
I need to store these in separate arrays, and then pull out a random selection from the array on click of a button. So each time the button is clicked, another four will be pulled from my array of 20 entries.
You can see my non-functioning page here: http://francesca-designed.me/create-a-status/
So the words on the side, when you click the button it'd run through the 20 words in the array and output them in each span, just four each time you click the button.
I looked on the PHP site and found this but I'm confused about which one to use.
Ultimately I would like to add this to a database as in the end if will be 50 words per pool, but for now I want to keep it all in one place while I practice.
<?php
$fruits = array (
"fruits" => array("a" => "orange", "b" => "banana", "c" => "apple"),
"numbers" => array(1, 2, 3, 4, 5, 6),
"holes" => array("first", 5 => "second", "third")
);
?>
There are two types of arrays:
array(
'key' => 'value',
'key' => 'value',
'key' => 'value',
)
and
array(
'value',
'value',
'value',
'value',
);
the latter is the same as:
array(
0 => 'value',
1 => 'value',
2 => 'value',
3 => 'value',
);
it's really how you want to use them...
if you loop through them with
foreach($array as $value) {
}
or
foreach($array as $key => $value) {
}
and there is no need for named keys, just use the second array.
edit:
$array = array(
'one' => array ('qwe1rty1','qwe1rty2','qwe1rty3'),
'two' => array ('qwe2rty1','qwe2rty2','qwe2rty3'),
'three' => array ('qwe3rty1','qwe3rty2','qwe3ert3'),
);
$array['one'][2] === 'qwe1rty3' (index starts at 0)
$array['three'][0] === 'qwe3rty1'
foreach($array['one'] as $key => $value) {
echo $key .' : ' $value;
}
gives
0 : qwe1rty1
1 : qwe1rty2
2 : qwe1rty3
Here is an example that is similar to what you're describing:
$words = array("tasty", "wretched", "simple", "gnarly", "fruitful", "cleeeever");
echo $words[1]; //prints wretched
for($i=0;$i<4;$i++) {//prints array in original order
echo $words[$i].'<br/>';
}
shuffle($words);
for($i=0;$i<4;$i++) {//prints shuffled array
echo $words[$i].'<br/>';
}
I have a variable number of multidimensional arrays but all with the same 4 possible values for each item.
For example:
Array
(
[companyid] => 1
[employeeid] => 1
[role] => "Something"
[name] => "Something"
)
but every array may have a different ammount of items inside it.
I want to turn all the arrays into one single table with lots of rows. I tried array_merge() but I end up with a table with 8, 12, 16... columns instead of more rows.
So... any ideas?
Thanks
Didn't test it, but you could try the following:
$table = array();
$columns = array('companyid' => '', 'employeeid' => '', 'role' => '', 'name' => '');
foreach($array as $item) {
$table[] = array_merge($columns, $item);
}
This should work since the documentation about array_merge say:
If the input arrays have the same string keys, then the later value
for that key will overwrite the previous one.
So you either get the value of the current item or a default value that you can specify in the $columns array.
$array1=Array
(
"companyid" => 1,
"employeeid" => 4,
"role" => "Something",
"name" => "Something",
);
$array2=Array
(
"companyid" => array(2,2,2),
"employeeid" => 5,
"role" => "Something2",
"name" => "Something2"
);
$array3=Array
(
"companyid" => 3,
"employeeid" => 6,
"role" => "Something3",
"name" => "Something3"
);
//Using array_merge
$main_array["companyid"]=array_merge((array)$array1["companyid"],(array)$array2["companyid"],(array)$array3["companyid"]);
$main_array["employeeid"]=array_merge((array)$array1["employeeid"],(array)$array2["employeeid"],(array)$array3["employeeid"]);
for($i=0;$i<count($main_array["companyid"]);$i++)
echo $main_array["companyid"][$i] + "<br />";
for($i=0;$i<count($main_array["employeeid"]);$i++)
echo $main_array["employeeid"][$i] + "<br />";
I've tested the code above and seems right.
You coult also improve this code into a DRY function.
I have 2 arrays. The keys represent the player id in a game (and is the same in both arrays) and the value represents the Ping in one and the score in the other. What I am trying to do is get the Player ID (key) that has the highest ping and the lowest score. I can't get my head around any of the sorts that would do this.
I don't have to use 2 arrays, I just don't know how else to do it.
Thanks.
LIVE Demo: http://codepad.org/46m3mHIH
Arranging this type of architecture would work better...
$players = array(
array(
"name" => "l337 H4x0r",
"score" => 10432,
"ping" => 0.35
),
array(
"name" => "El Kabooom",
"score" => 19918,
"ping" => 0.45
),
array(
"name" => "Kapop",
"score" => 10432,
"ping" => 0.38
)
);
Then you could more efficiently sort your multi-dimensional array, and retrieve your $lowestScore and $highestPing values.
$playersScore = subval_sort($players,'score');
$lowestScore = $playersScore[0]['score'];
$playersPing = subval_sort($players,'ping');
$HighestPing = $playersPing[ count($players)-1 ]['score'];
function subval_sort($a,$subkey) {
foreach($a as $k=>$v) {
$b[$k] = strtolower($v[$subkey]);
}
asort($b);
foreach($b as $key=>$val){
$c[] = $a[$key];
}
return $c;
}
A bit unclear whether you're looking for two separate sorts, or 1 combined. If separate then the asort() function will sort based on the values while maintaining the correct key=>value association. Just use this against each array.