PHP Randomly select an array from an multidimensional array [duplicate] - php

This question already has answers here:
Get random item from array [duplicate]
(4 answers)
multi dimensional array in random order
(4 answers)
Closed 9 years ago.
So I have this array of objects. From which I want to take at random one of the objects from the array, and use it for its intended purpose. I have tried array_rand() but that only returned a random value from one of the arrays within. Is there a method similar to array_rand() that will let me use the whole array as the variable rather than a value pluked from within it?
Example Array:
Array
(
[0] => stdClass Object
(
[id] => 10003
[state] => CA
)
[1] => stdClass Object
(
[id] => 10003
[state] => CA
)
[2] => stdClass Object
(
[id] => 10006
[state] => CA
)
)
What I want to do when doing something similar to array_rand() is end up with a variable that is
[0] => stdClass Object
(
[id] => 10006
[state] => CA
)
or similar

From array_rand documentation:
[array_rand] picks one or more random entries out of an array, and returns the
key (or keys) of the random entries.
To summarize: if you want to retrieve a random value from an array, you need to use the random key provided by array_rand to access it.
Solution, assuming your array is stored in $obj:
$random_obj = $obj[array_rand($obj));

Related

How to set array of array in single array in php [duplicate]

This question already has answers here:
How to Flatten a Multidimensional Array?
(31 answers)
Closed 3 years ago.
Following is my array
Array
(
[0] => Array
(
[1] => Beanie
)
[1] => Array
(
[2] => Cap
)
[2] => Array
(
[1] => Beanie with Logo
)
)
I want this into a single array like set key and value of array.
array(
[1]=>Beanie,
[2]=>Cap,
[1]=>Beanie with Logo,
)
Demo Link.
You can do,
array_merge(...$arr);
Splat operator will expose to all the values of array internally, to flatten array.
Your expected output is not possible in any coding language with
arrays.
Note: Indexes are mean to be unique, don't issue over its uniqueness :)

Access Variable Member [duplicate]

This question already has answers here:
How can I access an array/object?
(6 answers)
Closed 5 years ago.
I have an array variable $array like this
$array = Array
(
[results] => stdClass Object
(
[successc] => stdClass Object
(
[926] => stdClass Object
(
[transaction_id] => xx
[transaction_code] => xx
[status] => xx
[amount] => 5
)
)
[success] => Array
(
[0] => Successful transaction
)
)
)
I want to access the transaction_id element. The 926 is a variable value. It could very well be 927 or 928. It comes from another object $cc. Would it be correct to access the transaction_id using the following code?
$x = $cc->id;
$transaction_id = $array['results']->successc->{$x}->transaction_id;
Your approach is not bad, but the code structure looks more like an array.
To convert to a full array, you can encode to json en decode to array.
$array = json_decode(json_encode($array), true);
When TRUE, returned objects will be converted into associative arrays.
So you can access each level of $array as array element.

PHP - Access array in array [duplicate]

This question already has answers here:
How can I access an array/object?
(6 answers)
Accessing Arrays inside Arrays In PHP
(4 answers)
Closed 7 years ago.
I am working with response from Youtube Data API and I don't know how to read each values in the array.
Array
(
[0] => youtube#channelListResponse
[1] => "X"
[2] => Array (
[totalResults] => 1
[resultsPerPage] => 1
)
[3] => Array (
[0] => Array
(
[kind] => youtube#channel
[etag] => "XX"
[id] => XXX
)
)
)
When I try to access [id] with echo $array[3]['id'] it returns Notice: Undefined offset: 3
AS Max said you can access single value in array in array by
$arrayName[index]['key']
Example You can access 'kind' with
$arrayName[3]['kind']
Since, inner level array is key value paired you need to specify key instead of index.
If you want to access all value, you can do it with foreach loop and check type of each value use'gettype()' method. if type is array then use same function recursively.

strip array with only one item in it without looping thru it and not knowing its index [duplicate]

This question already has answers here:
Reset PHP Array Index
(4 answers)
Closed 8 years ago.
Array
(
[2] => stdClass Object
(
[name] => test-song-poll-03
[description] => test-song-poll-03
[created_at] => 2014-05-02T23:19:06Z
[count] => stdClass Object
(
[approved] => 26638
[pending] => 0
[rejected] => 36923
[total] => 63561
)
[tpm] => 47
[approved_tpm] => 9
[pct] => 2
)
)
I have a function that uses array_filter and it returns what you see above. It will only return one object within the array. I do not know what the array index will be, but I know there will only be one item in the array. Is there an array function that strips down the array and just returns the content of it, since I don't need an array with just one item in it.
You should use:
$x = array_values($yourArrayName);
echo $x[0];
You can also use:
echo current($yourArrayName);

How to merge two arrays of objects [duplicate]

This question already has answers here:
Merge rows of two arrays containing objects by first level index
(3 answers)
Closed 5 months ago.
A:
Array (
[0] => gapiReportEntry Object (
[metrics:private] => Array (
[visits] => 1036
[pageviews] => 2046
[bounces] => 693
[entrances] => 1036
)
[dimensions:private] => Array (
[date] => 20110114
)
)
)
B:
Array (
[0] => gapiReportEntry Object (
[metrics:private] => Array (
[goal1Completions] => 1
)
[dimensions:private] => Array (
[date] => 20110114
)
)
)
C:
Array (
[0] => gapiReportEntry Object (
[metrics:private] => Array (
[visits] => 1036
[pageviews] => 2046
[bounces] => 693
[entrances] => 1036
[goal1Completions] => 1
)
[dimensions:private] => Array (
[date] => 20110114
)
)
)
I want to merge(A,B) and get C.
I don't know the reason of such question, but here is solution:
//lets think $A - A - array, $B - B array
$a1 = (array)$A[0];
$b1 = (array)$B[0];
$c = array_merge($a1, $b1);
print_r($result);
//shows your Array, but not object.
//You can create object using printed resulted array.
For your specific case, let's be clear that you want to merge two arrays that are contained within objects contained within arrays. That being said, knowing how the resultant object was to be used (do you just need the data from those arrays, or does the rest of the object's instance matter?) would help give you an answer. tl;dr:
$temparray = array_merge($A[0]->metrics, $B[0]->metrics);
$C->methodToSetMetricsArray($temparray);
Where the above methodToSetMetricsArray() does what it says, since the array is private and can't be set directly.
First of all I'm not saying this is the end all of answers to this question, but it's been nine months and I feel the question hasn't been answered, while it does have it's uses.
From what I understand you have two (or more) arrays, consisting of multiple objects, who hold different attributes of the same object. As for instance in the next example:
ArrayedObjects1=array(
[0]=>stdClass Object
(
[id] => 1
[name] => foo
)
[1] => stdClass Object
(
[id] => 51
[name] => bar
)
)
ArrayedObjects2=array(
[0]=>stdClass Object
(
[length] => 195
[color] => blue
)
[1] => stdClass Object
(
[length] => 100
[name] => purple
)
)
Use cases could be for very large projects where multiple databases are used to store single values of the same object and simple join queries aren't possible.
These two arrays can be joined by using two functions I made, which simply allow for a unspecified amount of arrays to be joined together.
class FooBar {
public function mergeArrayedObjects(){
# We generate a new empty array to return from the function, to which we merge the existing arrays
$returnResponse=array();
# Then we establish the the number of arguments passed to the function
$numArgs=func_num_args();
# As objects are stored within an array of equal length, we loop through the first
for($i=0;$i<count(func_get_arg(0));$i++){
# For each key within the array we merge all existing arrays. We get this number from the number of arguments
# First we check if there already exists an entry into the returnRespone array with the current key. Two choices:
# Case 1 => no: create one by merging the first two arrays into this new array
# Case 2 => yes: merge the existing entry with the next array and recreate it
# BTW we correct $numArgs in the for-loop, as we add 1 to $j in the second case to exclude duplication of work
for($j=0;$j<($numArgs-1);$j++){
# Seems like you can't check on empty with func_get_arg(), so store it in a variable
# We do this as no merge is needed if the array is empty, or the key is empty
$isempty=func_get_arg($j+1);
if(!empty($isempty)||!empty($isempty[$i])){
if(!$returnResponse[$i]){
$array1=func_get_arg($j);
$array2=func_get_arg($j+1);
$returnResponse[$i]=self::mergeObjects($array1[$i],$array2[$i]);
}
else{
$array1=func_get_arg($j+1);
$returnResponse[$i]=self::mergeObjects($returnResponse[$i],$array1[$i]);
}
}
}
}
# Then we return the arrayed objects
return $returnResponse;
}
public function mergeObjects($obj1,$obj2){
# Function to merge objects
$merged_obj= (object) array_merge((array) $obj1, (array) $obj2);
return $merged_obj;
}
}
This returns the following array:
$joinArrays=new FooBar;
$joinedArray=$joinArrays->mergeArrayedObjects(ArrayedObjects1,ArrayedObjects2);
$joinedArray=array(
[0]=stdClass Object
(
[id] => 1
[name] => foo
[length] => 195
[color] => blue
)
[1] => stdClass Object
(
[id] => 51
[name] => bar
[length] => 100
[name] => purple
)
)
As I said this can be used for an unlimited amount of arrays. If there's a faster way, feel free to let me know. I needed this for joining the results from queries between different DB's so I just wrote to as this does the job and is quite flexible at the same time.
This can also be extended to check if one of the entries within the object is an array and do an array_merge ofcourse, it would add two lines of code.
You want a deep merge with custom Php class. There is no such function built-in.
But if you can transform your Php objects to array, you could get advantage of array_merge_recursive functions (see http://php.net/manual/fr/function.array-merge-recursive.php).

Categories