How to randomize an array of objects in PHP? - php

I have this example of an array of objects and I need to randomize it each time I do a foreach loop.
Looks like shuffle works only on arrays.
One thing is that I cant convert this into an array, because then it will become a STD object which I can't use, because of the way my mapper works.
array(48) {
[0] => object(Friends_Model_Friends)#142 (4) {
["_id":protected] => NULL
["_tal":protected] => object(stdClass)#194 (3) {
["thumb"] => object(stdClass)#196 (6) {
["id"] => string(8) "10884697"
["type"] => string(1) "2"
["gallery"] => string(1) "1"
}
}
["_friend":protected] => string(7) "3492149"
["_dependent_table":protected] => NULL
}
[1] => object(Friends_Model_Friends)#195 (4) {
["_id":protected] => NULL
["_tal":protected] => object(stdClass)#143 (3) {
["thumb"] => object(stdClass)#202 (6) {
["id"] => string(8) "11160632"
["type"] => string(1) "2"
["gallery"] => string(1) "1"
}
}
["_friend":protected] => string(7) "3301541"
["_dependent_table":protected] => NULL
}
....
Any ideas on shuffling this?
edit: Zend_Debug::dump(shuffle($object)); returns bool(true)

<?php
$my_array;
echo '<pre>'; print_r($my_array); echo '</pre>';
shuffle ($my_array);
echo '<pre>'; print_r($my_array); echo '</pre>';
?>
Try this code

But the objects are in an array, not another object so you can use shuffle...

Shuffle always returns a boolean:
bool shuffle ( array &$array )
So you can't return it like
return shuffle( $myAwesomeArray );
This is what I just did and I wondered why it didn't give anything back, as you're probably expecting your shuffled array back.
You just have to call it like this
shuffle( $myAwesomeArray );
return $myAwesomeArray;
And all should work just fine.

Related

PHP suppress part of array if duplicate

I have an array of database objects and I'm using foreach() to present the names and projects. Good, now the customer doesn't want duplicate names for when one person has multiple projects. This has to do with variable scope and this is my failed attempt to pull this stunt off. Here's a partial var_dump of the array of objects.
array [
0 => {
["lastName"]=>
string(1) "w"
["projectName"]=>
string(29) "Bone density scanner analysis"
}
1 => {
["lastName"]=>
string(1) "w"
["projectName"]=>
string(29) "analysis of foot"
}
]
What I want to end up with is:
array [
0 => {
["lastName"]=>
string(1) "w"
["projectName"]=>
string(29) "Bone density scanner analysis"
}
1 => {
["lastName"]=>
string(1) ""
["projectName"]=>
string(16) "analysis of foot"
}
]
Here's what I was thinking that doesn't seem to work:
function suppress_name($name){
global $string;
return ($name == $string) ? '' : $string;
}
function overall() {
//$result = database call to get objects
foreach ($result as $item) {
$string = $item->lastName;
$rows = array('Name' => suppress_name($item->lastName), 'project' => $item->projectName);
}
}
Researching I see several references to array_unique() which I use for a flattened array, but I can't see that it would help me here. OK, I thought I could make a function, like the above, to handle duplicates and use the $global but think I'm not grasping how to use globals in this instance. I'm happy to be pointed to a better way, or better search terms. Does this make sense?
Here is a possible approach to your solution, where we store the last names in a one dimensional array then check against it through each iteration of the array. If the lastName is in the array then set the value to ''.
Note the use of the reference (&).
<?php
$arrays = array(
array('lastName' => 'w', 'projectName' => 'Bone density scanner analysis'),
array('lastName' => 'w', 'projectName' => 'analysis of foot')
);
$last_names = array();
foreach($arrays as &$array){
if( in_array($array['lastName'],$last_names) ){
$array['lastName'] = '';
}else{
$last_names[] = $array['lastName'];
}
}
echo '<pre>',print_r($arrays),'</pre>';
It would be easier to work with nested arrays
array [
0 => {
["lastName"]=> string(1) "w"
["projects"]=> array [
0 => {
["projectName"] => string(29) "Bone density scanner analysis"
}
1 => {
["projectName"]=> string(16) "analysis of foot"
}
1 => {
["lastName"] => string(1) "x"
["projects"] => array [
0 => {
["projectName"] => string(16) "analysis of head"
} ]
}
]

PHP how to echo array values which have no name attached to them

How can I put each value into a variable?
I tried using foreach but I am not sure what to put in the ??? area
I tried also using echo $results[14], but I received an undefined error.
foreach($results['ups'] as $result) {
echo $result['???']. '<br>';
}
output:
array(1) {
["ups"]=> array(4) {
[14]=> string(5) "62.89"
["01"]=> string(5) "30.47"
["02"]=> string(5) "20.76"
[11]=> string(5) "20.96"
}
}
Array
(
[ups] => Array
(
[14] => 62.89
[01] => 30.47
[02] => 20.76
[11] => 20.96
)
)
You put nothing in the []:
foreach($results['ups'] as $result) {
echo $result + '<br>';
}
should do it.
array_keys() should return all defined keys, so try eg.
$keys = array_keys($results['ups']);
echo $results['ups'][$keys[0]];
echo $results['ups'][$keys[1]];
to access the first and second element.
simply use
echo $results['ups']['14'];
if you don't know the index that you want to access or maintaining key index is not relevant.
sort $results['ups'];
echo $results['ups'][0];

PHP foreach subarray in array

I'm trying to parse an array that looks like this:
array(1) {
["StrategischeDoelstellingenPerDepartement"] => array(412) {
[0] => array(5) {
["CodeDepartement"] => string(8) "DEPBRAND"
["NummerHoofdstrategischeDoelstelling"] => string(1) "1"
["Nummer"] => string(2) "27"
["Titel"] => string(22) "DSD 01 - HULPVERLENING"
["IdBudgetronde"] => string(1) "2"
}
[1] => array(5) {
["CodeDepartement"] => string(8) "DEPBRAND"
["NummerHoofdstrategischeDoelstelling"] => string(1) "2"
["Nummer"] => string(2) "28"
["Titel"] => string(24) "DSD 02 - Dienstverlening"
["IdBudgetronde"] => string(1) "2"
}
[2] => array(5) {
["CodeDepartement"] => string(8) "DEPBRAND"
["NummerHoofdstrategischeDoelstelling"] => string(1) "2"
["Nummer"] => string(2) "29"
["Titel"] => string(16) "DSD 03 - KLANTEN"
["IdBudgetronde"] => string(1) "2"
}
...
(The array goes on but it's too big to post it here in its entirety)
I can do a foreach loop on the array like this:
foreach($my_arr->StrategischeDoelstellingenPerDepartement as $row){
echo "i found one <br>";
}
However, I want to do the same thing on other arrays and I want to make the function generic. The first key (StrategischeDoelstellingenPerDepartement in this case) can sometimes change, which is why I'd like to do it generically. I've already tried the following:
foreach($my_arr[0] as $row){
echo "i found one <br>";
}
But then I get the following notice, and no data:
Notice: Undefined offset: 0 in C:\Users\Thomas\Documents\GitHub\Backstage\application\controllers\AdminController.php on line 29
This is probably a silly question, but I'm new to PHP and this seemed like the right way to do it. Obviously, it isn't. Can anyone help me out, please?
Use reset to grab the first element of $my_arr without knowing the key name:
$a = reset($my_arr);
foreach($a as $row){
echo "i found one <br>";
}
Shift the sub-array off the main array and loop over it:
$sub = array_shift($my_arr);
foreach ($sub as $row) {
echo $row['Titel'], "<br>";
}
You are trying to do is object, not array $my_arr->StrategischeDoelstellingenPerDepartement.
You could use isset() to check the index existence:
if(isset($my_arr['StrategischeDoelstellingenPerDepartement'])){
foreach($my_arr['StrategischeDoelstellingenPerDepartement'] as $row){
echo "i found one <br>";
}
}
Or, you could use array_values() to ignore the array keys and to make it an index array:
$my_new_arr = array_values($my_arr);
foreach($my_new_arr as $row){
echo "i found one <br>";
}
Use current ref : http://in3.php.net/manual/en/function.current.php
$a = current($my_arr);
foreach($a as $row){
echo "i found one <br>";
}

PHP radom output from key value array

How can I get the follow thing done.
The follow array I have:
array(2) { [0] => array(3) {
["id"] => string(1) "5"
["avatar"] => string(15) "4e0d886ee9ed3_n"
["username"] => string(5) "testuser1"}
[1] => array(3) {
["id"] => string(1) "1"
["avatar"] => string(15) "4e25bc58b6789_w"
["username"] => string(6) "testuser2"
}
}
I want to create a array with just one user in it, but it has to be random. It can be like
user with id=5, id=1 or a hole other user (when there are more users).
Did you try, something like:
$rand = array_rand($your_array);
http://fr2.php.net/manual/en/function.array-rand.php
Try using array_rand().
$randomKey = array_rand($yourArray);
$randomUserId = $yourArray[$randomKey]['id'];
Simple.
$rand_user = array_rand($your_array);
PHP Manual: array_rand

Get specific key value pair from multidimensional array

I have the following array:
array(2) {
[0] => array(3) {
["submission_id"] => int(28)
["date"] => string(22) "2010-10-18 15:55:33+02"
["user_id"] => int(12)
}
[1] => array(3) {
["submission_id"] => int(37)
["date"] => string(22) "2010-11-21 16:02:07+01"
["user_id"] => int(23)
}
I want to get only the user_id key values from this array. I could obviously loop over it, but I was wondering if there was a quicker way.
You could use array_map (might not be quicker though, as it will make a function call per array element):
function getUserId($a) {
return $a['user_id'];
}
$user_ids = array_map('getUserId', $array);
Apart from that, looping is the only way (array_map makes loop anyway).
You can access only the user_id values like this if you know the array index you want to access:
$arr = your array here..
echo $arr[0]['user_id'];
echo $arr[1]['user_id'];

Categories