Create array from objects php - php

I have a JSON result file that is decoded into an array of objects. I am using a Foreach to find the correct player and then wish to create an array with all the information under the correct player.
This is a snippet of the array of objects:
object(stdClass)#3 (1) {
["result"]=>
object(stdClass)#4 (18) {
["players"]=>
array(10) {
[0]=>
object(stdClass)#5 (24) {
["account_id"]=>
int(72775718)
["player_slot"]=>
int(0)
["hero_id"]=>
int(46)
["item_0"]=>
int(50)
["item_1"]=>
int(139)
["item_2"]=>
int(149)
["item_3"]=>
int(147)
["item_4"]=>
int(168)
["item_5"]=>
int(116)
["kills"]=>
int(26)
["deaths"]=>
int(10)
["assists"]=>
int(9)
["leaver_status"]=>
int(0)
["gold"]=>
int(1622)
["last_hits"]=>
int(285)
There are several players in this, and I am using the account_id to find the correct player with:
foreach ($data_decoded->result->players as $val){
if($val->account_id == $this->PlayerID){
echo "found you!"."\n";
}
How do I then create an array with all of the subsequent results? For example, underneath the account_id, I would like to store all of that information (player_slot, hero_id, etc.) Do I need to use another foreach? If so I honestly don't know how to word it.
I have tried:
foreach ($data_decoded->result->players as $val){
if($val->account_id == $this->PlayerID){
echo "found you!"."\n";
foreach($val as $test){
$dataarray=array($test);
}
but this only adds the values that are on the same "level" (poor terminology) as $val, and not the subsequent values?

If you really want to change it into an array you can simply cast it:
if ($val->account_id == $this->PlayerID) {
$dataarray = (array) $val;
}
Demo: https://eval.in/116967

Related

Inefficient nested foreach loop

I have two array and want to merge it by using key of main array;
// $result : main dataset (multidimensional array)
// $referenceData : data related with main dataset and want to merge it into main dataset (multidimensional array)
if ($result) {
foreach ($result as $key => $val) {
foreach ($referenceData[$val['id']] as $refKey => $refVal) {
$result[$key][$refKey] = $refVal;
}
}
}
The thing is, when the result is high (even for 1000 elements on each) it takes more than 5-10 seconds which is quite unexpected for me.
I tried to use array_merge and array_merge_recursive instead of two foreach but I kept failing. Is there any way I could improve the logic? Thanks in advance.
Edit (added sample array);
result :
array(1) {
[0]=>
array(6) {
["id"]=>
string(5) "13020"
["name"]=>
string(23) "Data Stream 1"
["rank"]=>
string(1) "3"
["data_1"]=>
string(2) "63"
["data_2"]=>
string(2) "256"
["data_3"]=>
string(3) "469"
}
}
referenceData:
array(1) {
[13020]=>
array(5) {
["percent"]=>
float(20.987654320988)
["count_min"]=>
string(1) "1"
["count_max"]=>
int(2)
["checked"]=>
bool(false)
["cond_id"]=>
string(1) "0"
}
}
You need to make the first array structure exactly like the second array so that you can easily merge them. To do so you can do like below : (Its a reference code, you need to change it at your end)
$rows = $db->table('<table name>')->get()->getResultArray();
$result = [];
foreach ($rows as $row) {
$result[$row['id']] = $row;
}
Once both arrays have a similar structure, then you can go for a single foreach() and + operator to combine child arrays.
$finalArray = [];
foreach($result as $key=>$value){
$finalArray[$key] = $value+$referenceData[$key];
}
print_r($finalArray);
Output: https://3v4l.org/qBa4V
Note: if you want to re-index this new array (in case you want indexes like 0,1,2... so on) then you can do:
$finalArray = array_values($finalArray);

Trouble getting data from an array in PHP

I've got this array:
array(1) {
["sensory-evaluation"]=> array(6) {
["name"]=> string(18) "Sensory Evaluation"
["value"]=> string(43) "10/22/2015 at 6:00pm | 11/25/2015 at 6:00pm"
["position"]=> string(1) "3"
["is_visible"]=> int(1)
["is_variation"]=> int(1)
["is_taxonomy"]=> int(0)
}
}
I need to be able to get the data from ["value"]. If I do $arr["sensory-evaluation"]["value"] I can get it but the problem is ["sensory-evaluation"] will be different for each element in my array so I need a way to abstract that part but I haven't been able to figure it out.
If you have only one item in the array as you show then:
echo current($arr)['value'];
If you don't know if it exists:
if(isset(current($arr)['value'])) {
echo current($arr)['value'];
}
You could also do:
echo array_values($arr)[0]['value'];
why not use a for each
function getValue($arr){
foreach ($arr as $key => $value) {
var $subArray=$arr[$key];
if( array_key_exists ('value' ,$subArray))
return $arr[$key]['value'];
}
}

php array loop to get array

I have a $date array like this:
[1]=> array(11) {
["meetingname"]=> string(33) "win2008connectcurrent0423131"
[0]=> array(3) {
["scoid"]=> string(7) "3557012"
["datecreated"]=> string(19) "2013-05-23 10:02:39"
["numparticipants"]=> string(1) "3"
}
[1]=> array(3) {
["scoid"]=> string(7) "3557012"
["datecreated"]=> string(19) "2013-05-23 14:40:06"
["numparticipants"]=> string(1) "3"
}
}
foreach($date[0] as $key => $meetings){
print "$key = $meetings\n";////yields scoid = 3557012
}
And, as you can see above, I am looping over individual elements. The first element (not indexed) is always meetingname; the rest of the elements are indexed and themselves contain arrays with three elements in each array--in the above code they are [0] and [1].
What I need to do is make the $meetings as an array containing [0] and then [1] etc, depending on the number of elements. So essentially, the output for print should be an array (I can also use var_dump) with key/values of [0] but right not it only outputs individual keys and their values, for example, as you can see above, scoid=3557012. I will need, something all keys/values in the $meetings variable, something like:
{
["scoid"]=> string(7) "3557012"
["datecreated"]=> string(19) "2013-05-23 10:02:39"
["numparticipants"]=> string(1) "3"
}
How can I fix the foreach loop for that?
please Try this. hope it help.
foreach($date as $key => $meetings){
if($key == "meetingname")
continue;
else
print "$meetings\n";
}
You can just create a new array and add the meetings to that one
<?php
$meetings = array();
foreach($date[1] as $key=>$meeting) {
if (!is_int($key))
continue; //only handle numeric keys, incase you ever change the name of the first key 'meetingname'
$meetings[] = $meeting
}
var_dump($meetings);
?>

Modifying an array inside an array

So I need to modify the array in a memcached key-value pair. I need to remove one of the arrays inside the array. An example of what it looks like:
array(2) { [0]=> array(3) { ["username"]=> string(3) "Bob" ["id"]=> string(5) "14537" ["comment"]=> string(4) "cool"} [1]=> array(3) { ["username"]=> string(3) "Tom" ["id"]=> string(5) "14538" ["comment"]=> string(3) "yes"}}
If I know the values of username, id, and comment, how can I delete it? The generic queston: How can I delete array 0?
Considering the answer of doing a foreach loop, I tried
foreach($memcachedarray as $f){
if ($f['id'] == '14537'){
echo key($f);
}
}
But it spits out username
Edit- Ok
I searched some more and found I need to do this:
foreach($memcachedarray as $key => $f){
if ($f['id'] == '14537'){
echo $key;
}
}
That works!
If the Id's are unique across the system then you could use an associative array to store you data then unset the key, otherwise you would want to use a foreach loop to get the array key, then unset that key and recommit your new array back into memcache.

Alternative to foreach() PHP?

I am still very new to PHP and from all the examples that are around they all seem to use foreach statements.
e.g.
foreach ($variable as $row)
However I don't think I should be using this all the time, for example variables or objects I have an which only has one row or instance in an array.
I know its advantageous to use them for multiple rows which could be missed if you used a for loop.
But do I really need to use it just to echo one variable thats in an array?
e.g. for example this variable $stats
array(3) { ["user_interventions"]=> int(4) ["fastest_intervention"]=> array(1) { [0]=> object(stdClass)#22 (1) { ["duration"]=> string(8) "02:10:00" } } ["slowest_intervention"]=> array(1) { [0]=> object(stdClass)#23 (1) { ["duration"]=> string(8) "02:26:00" } } }
Thanks
if you know the 'address' of the value in your array, then there's no need for a loop:
echo $arr['user_interventions'][0]['duration']; // 02:10:00
More details here.
No, you do not need to use a foreach loop every time you need to access an array value. Your example could be used in the following manner...
echo $stats['fastest_intervention']['0']->duration; // Outputs: 02:10:00
Here's your variable dump with indentation (makes it easier to read).
array(3) {
["user_interventions"]=> int(4)
["fastest_intervention"]=> array(1) {
[0]=> object(stdClass)#22 (1) {
["duration"]=> string(8) "02:10:00"
}
}
["slowest_intervention"]=> array(1) {
[0]=> object(stdClass)#23 (1) {
["duration"]=> string(8) "02:26:00"
}
}
}
You need not to use foreach here but you can't just print $array
if you indexes of array you may print something like:
print 'Key is '.$array['key'].' but index is only'.$array['index'];
You just access the variables using []. print $array['key']

Categories