Adding Elements To An StdClass Array - PHP / Codeigniter - php

I have an array that is an stdClass. The output of that array is as follows :
Array
(
[0] => stdClass Object
(
[vendor_id] => 1
[user_id] => 1
[date_created] => 2013-06-12 16:48:38
[date_edited] =>
[status] => active
[user_firstname] => Stuart
[user_surname] => Blackett
)
)
What I would like to do is add two variables to this stdClass. They are "total_bookings" and "total_venues";
I currently am looping through the results and then getting a count to create the total. I would like to add those two vars to the end of that stdClass array.
My PHP is as follows :
$vendors = $this->po_model->get_all_vendors();
$this->template->set('total_vendors', count($vendors));
$count = 0;
foreach($vendors as $vendor)
{
$count++;
$total_venues = $this->po_model->get_count_venues($vendor->user_id);
$total_bookings = $this->po_model->get_count_bookings($vendor->user_id);
$vendors[$count]['total_venues'] = $total_venues;
$vendors[$count]['total_bookings'] = $total_bookings;
}
However, When I var_dump that my Array looks like this :
Array
(
[0] => stdClass Object
(
[vendor_id] => 1
[user_id] => 1
[date_created] => 2013-06-12 16:48:38
[date_edited] =>
[status] => active
[user_firstname] => Stuart
[user_surname] => Blackett
)
[1] => Array
(
[total_venues] => 6
[total_bookings] => 14
)
)
So my question is, How do I add total_venues and total_bookings to that stdClass()?
Thanks

$myArray[$indexOfObject]->total_venues = 6;
$myArray[$indexOfObject]->total_bookings= 14;
Your example:
foreach($vendors as $key => $vendor)
{
$total_venues = $this->po_model->get_count_venues($vendor->user_id);
$total_bookings = $this->po_model->get_count_bookings($vendor->user_id);
$vendors[$key]->total_venues = $total_venues;
$vendors[$key]->total_bookings = $total_bookings;
}

its an object, you should use object notations, not array notations. also change your move your count++ below these two instructions
$vendors[$count]->total_venues = $total_venues;
$vendors[$count]->total_bookings = $total_bookings;
$count++;

Related

How to insert item on every item in an array using PHP

I have this existing array
Array
(
[0] => stdClass Object
(
[userid] => 1
[user] => John Doe
)
[1] => stdClass Object
(
[userid] => 2
[user] => Mae Smith
)
)
I want to insert new item in each array like [randomNumber] => 50. So the final output must be like this
Array
(
[0] => stdClass Object
(
[userid] => 1
[user] => John Doe
[randomNumber] => 25
)
[1] => stdClass Object
(
[userid] => 2
[user] => Mae Smith
[randomNumber] => 50
)
)
I'm using php using for loop to insert the randomNumber every user
for($i=0 ; $i<count($users) ; $i++) {
// insert randomNumber here
$users[$i] = array('randomNumber' => rand(10,100));
}
It doesn't seems to work. What should be the proper way? Thanks
Iterate with a foreach, and as $user is an object, it will be passed to loop by reference:
foreach ($users as $user) {
$user->randomNumber = rand(10,100);
}
As you have an array of objects rather than arrays...
for($i=0 ; $i<count($users) ; $i++) {
// insert randomNumber here
$users[$i]->randomNumber = rand(10,100);
}
I think foreach function is better for you. and you have array of objects.
foreach ($users as $key => $value) {
$users[$key]->randomNumber = rand(10,100);
}

Get the highest, second highest and the lowest from the multidimensional array based on another value

In my code, I am getting an array like below
Array
(
[12247] => stdClass Object
(
[wid] => 12247
[uid] => 1626
[timestamp] => 1482021161
[weight_value] => 63.9
[nid] => 1195487
[source] => 0
[weight_entered] =>
)
[34843] => stdClass Object
(
[wid] => 34843
[uid] => 1632
[timestamp] => 1485298453
[weight_value] => 72.5
[nid] => 1206019
[source] => 8176
[weight_entered] =>
)
[35316] => stdClass Object
(
[wid] => 35316
[uid] => 1632
[timestamp] => 1485723529
[weight_value] => 54.2
[nid] => 1209357
[source] => 0
[weight_entered] =>
)
[35177] => stdClass Object
(
[wid] => 35177
[uid] => 1632
[timestamp] => 1485559176
[weight_value] => 53.3
[nid] => 1209357
[source] => 0
[weight_entered] =>
)
[12248] => stdClass Object
(
[wid] => 12248
[uid] => 1633
[timestamp] => 1481662016
[weight_value] => 56.6
[nid] => 1209357
[source] => 0
[weight_entered] =>
)
[12249] => stdClass Object
(
[wid] => 12249
[uid] => 1635
[timestamp] => 1479839680
[weight_value] => 54
[nid] => 1209357
[source] => 0
[weight_entered] =>
)
)
The array is order by the nid, timestamp, wid in descending order. I need to get an output array which will contain only the latest, second latest and the first weight values with the nid as an index. So that I will get the details of a particular nid only.
The output which I think about is like below and the logic behind that is
These multidimensional arrays have a value nid. I need to get the
latest, second latest and the first weight_value from a particular
nid. As the array is already sorted in descending order of time, I
just need to fetch the first, second and last values from each inner
array having common nid
Array
(
[1195487] => stdClass Object
(
[latest_weight] => 63.9
[second_latest_weight] =>
[first_weight] =>
)
[1206019] => stdClass Object
(
[latest_weight] => 72.5
[second_latest_weight] =>
[first_weight] =>
)
[1209357] => stdClass Object
(
[latest_weight] => 54.2
[second_latest_weight] => 53.3
[first_weight] => 54
)
)
I tried the code, but I am stuck up by not getting the proper logic to apply. Please help.
The code which I am trying is given below. But it is not full and not correct too.
if(!empty($history_details)){
$last_weight = 0;
$second_last_weight = 0;
$first_weight = 0;
$prev_nid = '';
$prev_wid = '';
$prev_count = 1;
foreach($history_details as $single_history){
if(empty($weight_array[$single_history -> nid]['field_weight_format'])){
$current_weight = $weight_array[$single_history -> nid]['field_weight_value']." lbs";
}
else{
$current_weight = str_replace('-', ' ', $weight_array[$single_history -> nid]['field_weight_format']);
}
if($prev_nid == '' || $prev_nid != $single_history -> nid){
$last_weight = $single_history -> weight_value;
if($prev_nid != $single_history -> nid){
$prev_count = 1;
}
}
else if($prev_count === 2){
$second_last_weight = $single_history -> weight_value;
$first_weight = $single_history -> weight_value;
}
else if($prev_count > 2 && $prev_nid != $single_history -> nid){
$first_weight = $history_details[$prev_wid] -> weight_value;
}
$prev_count++;
$prev_nid = $single_history -> nid;
$prev_wid = $single_history -> wid;
}
}
You can just sort by the weight within a group I guess.
function findInGroup($outerArray, $targetGroup) {
$array = array_filter($outerArray, function ($item) use ($targetGroup) {
return $item->nid == $targetGroup;
});
uasort($array,function ($a,$b) {
return $a->weight_value<=>$b->weight_value;
});
$first = reset($array);
$second = next($array);
$last = end($array);
return [ $first, $second, $last ];
}
Then you can do:
findInGroup($history_details,1209357);
Or you can do it for all groups via:
$keys = array_unique(array_map(function ($item) {
return $item->nid;
}, $history_details); //All distinct keys
$pluckedValues = array_map(function ($id) use ($history_details) {
return findInGroup($history_details, $id);
}, $keys); //Just the values for each distinct key
$values = array_combine($keys, $pluckedValues); //Combined with the key.
Of course this is not an optimal solution but would be a place to start.

Array group in php

I have the following array data:
[0] => stdClass Object
(
[schoolBin] => 110140014570
[schoolName] => школа-лицей № 66
[users] => 30
[tb0306_tb0301_id] => 514725
[tb0306_tb3002_id] => 17
[tb0306_countOfCorrectAnswers] => 14
[point] => 4
)
[1] => stdClass Object
(
[schoolBin] => 110140014570
[schoolName] => школа-лицей № 66
[users] => 30
[tb0306_tb0301_id] => 514725
[tb0306_tb3002_id] => 18
[tb0306_countOfCorrectAnswers] => 11
[point] => 4
)
So, i have many tb0306_tb0301_id from one schoolBin, and tb0306_tb0301_id has many tb0306_countOfCorrectAnswers of tb0306_tb3002_id. So i need to sum all tb0306_countOfCorrectAnswers of for all tb0306_tb0301_id of one schoolBin and i have many schoolBin, so i need to do the process for all schoolBin.
Tried the code:
$results = array();
foreach ($schoolResults as $schoolResult) {
$schoolBin = $schoolResult->schoolBin;
if (isset($results[$schoolBin])) {
$results[$schoolBin][] = $schoolResult;
} else {
$results[$schoolBin] = array($schoolResult);
}
}
But could not sum tb0306_countOfCorrectAnswers for one tb0306_tb0301_id.
Any helps guys!
here is the code to sum the tb0306_countOfCorrectAnswers for tb0306_tb0301_id of schoolBin. I use # to ingnore the worning for uninitial value.
$results = array();
foreach ($schoolResults as $schoolResult) {
#$result[$schoolResult->schoolBin][$schoolResult->tb0306_tb0301_id] += $schoolResult->tb0306_countOfCorrectAnswers
}

Write JSON into a file with PHP

I have this JSON-File here
{
"id" : "bf75b277-169b-49da-8ab1-b78b8dfg1b43-e25c7f28b3",
"ts" : "1372751172664",
"connected" : {
"ssid" : "eduroam",
"bssid" : "00:0f:f9:eb:08:81",
"rssi" : "-62",
"speed" : "53"
},
"configured" : [
{
"ssid" : "eduroam",
"bssid" : "null",
"keyMgmnt" : ["2", "3"],
"grCiphers" : ["0","1","2","3"]
},
{
"ssid" : "foobar",
"bssid" : "null",
"keyMgmnt" : ["0"],
"grCiphers" : ["0","1","2","3"]
}
],
"location" : {
"prov" : "network",
"lat" : "52.3793203",
"lon" : "9.7231332",
"acc" : "22.777"
}
}
and I'm trying to get the key-value-pairs out into a file (and later into a mysql-database).
I am having trouble to go along the nested structure. Maybe I do not understand it correctly?
$LOGPATH = "/var/www/test/";
$out = fopen($LOGPATH."testlog.log", "a");
$result = file_get_contents('php://input');
$data = json_decode($result, true);
$value = $data;
$test = array();
This line beneath causes me headaches, how can I say get the key-value-pairs of "connected"?
Trying $test = $data['connected'] did not work, as the output simply is a "{" and nothing more...
$test = $data;
fwrite($out, "test \n");
fwrite($out, $test);
fwrite($out, "\n");
foreach ($test as $entry){
fwrite($out, $entry);
fwrite($out, "\n");
}
Any idea how to extract the key-value-pairs and/or help me understand the structure?
This should get you on the right track
foreach($data['connected'] as $key => $value){
echo 'Key: '.$key.' Value:'.$value.'<br>';
}
json_decode() will dump JSON into regular array. You can do print_r() or var_dump() on it, to see the structure of the array. So to get your connected leaf you do:
$connected = $data['connected'];
You can then iterate over it:
foreach( $connected as $key=>$val ) {
echo $key . ": " . $val;
}
Got it, thanks to you guys!
// Get a request from i.e. a webpage (this is a webservice)
$jsonArray = file_get_contents('php://input');
// put the JSON-Data into an array
$jsonData = json_decode($jsonArray, true);
// You can simply choose the entry-points. As they do not change for me, they are hardcoded in here, else you had to use something like a for-loop to extract them
$jsonConnect = $jsonData['connected'];
$jsonLocation = $jsonData['location'];
$jsonConfigured = $jsonData['configured'];
// walk through the JSON-Data and extract the values, although the array has more than 2 levels, you can select your entry-point and walk from there on, which makes this quite easy
for($i = 0; $i < count($jsonConfigured); $i++){
// keyMgmnt itself is an array and I want to concatenate all of its values and put it into a single field in my MySQL-DB, so implode() is used
$keyMgmnt = implode(",", $jsonConfigured[$i]['keyMgmnt']);
$grCiphers = implode(",", $jsonConfigured[$i]['grCiphers']);
$ssid = $jsonConfigured[$i]['ssid'];
$bssid = $jsonConfigured[$i]['bssid'];
// from here on I simply put the variables into my MySQL-DB
$sql_configured = "INSERT INTO configured (keyMgmnt, grCiphers, ssid, bssid) VALUES ('$keyMgmnt', '$grCiphers', '$ssid', '$bssid')";
mysql_query($sql_configured) or die ("Failure in configured");
}
$sql_connected = "INSERT INTO connected (rssi, speed, ssid, bssid) VALUES ('$jsonConnect[rssi]', '$jsonConnect[speed]', '$jsonConnect[ssid]', '$jsonConnect[bssid]')";
$enterConnected = mysql_query($sql_connected) or die("Failure in connection!");
$sql_location = "INSERT INTO location (lat, prov, lon, acc) VALUES ('$jsonLocation[lat]', '$jsonLocation[prov]', '$jsonLocation[lon]', '$jsonLocation[acc]')";
$enterLocation = mysql_query($sql_location) or die("Failure in location!");
Thanks again!
Case closed.
PS: The structure of the JSON-Data. You get it by using "print_r()" or "var_dump()".
(
[id] => bf75b277-169b-49da-8ab1-b78b80f51b43-e25c7f28b3
[ts] => 1372751172664
[connected] => Array
(
[ssid] => eduroam
[bssid] => 00:0f:f7:eb:08:81
[rssi] => -62
[speed] => 54
)
[configured] => Array
(
[0] => Array
(
[ssid] => eduroam
[bssid] => null
[keyMgmnt] => Array
(
[0] => 2
[1] => 3
)
[grCiphers] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
)
)
[1] => Array
(
[ssid] => foobar
[bssid] => null
[keyMgmnt] => Array
(
[0] => 0
)
[grCiphers] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
)
)
)
[location] => Array
(
[prov] => network
[lat] => 52.3793203
[lon] => 9.7231332
[acc] => 22.777
)
)
(
[id] => bf75b277-169b-49da-8ab1-b78b80f51b43-e25c7f28b3
[ts] => 1372751172664
[connected] => Array
(
[ssid] => eduroam
[bssid] => 00:0f:f7:eb:08:81
[rssi] => -62
[speed] => 54
)
[configured] => Array
(
[0] => Array
(
[ssid] => eduroam
[bssid] => null
[keyMgmnt] => Array
(
[0] => 2
[1] => 3
)
[grCiphers] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
)
)
[1] => Array
(
[ssid] => foobar
[bssid] => null
[keyMgmnt] => Array
(
[0] => 0
)
[grCiphers] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
)
)
)
[location] => Array
(
[prov] => network
[lat] => 52.3793203
[lon] => 9.7231332
[acc] => 22.777
)
)

Counting unique arrays inside the array in PHP?

I have some array containing other arrays:
Array
(
[0] => Slip Object
(
[userId:protected] => 1
[parentSlipId:protected] => 0
[id:protected] => 25
[madeDatetime:protected] => 2011-04-19 17:13:09
[stake:protected] => 34.00
[status:protected] => 6
)
[1] => Slip Object
(
[userId:protected] => 1
[parentSlipId:protected] => 0
[id:protected] => 25
[madeDatetime:protected] => 2011-04-19 17:13:09
[stake:protected] => 34.00
[status:protected] => 6
)
[2] => Slip Object
(
[userId:protected] => 1
[parentSlipId:protected] => 0
[id:protected] => 24
[madeDatetime:protected] => 2011-04-18 11:31:26
[stake:protected] => 13.00
[status:protected] => 6
)
)
What's the best way of counting unique arrays?
Off the top of my head you could try:
$hashes = array();
$uniques = 0;
foreach($array as $slip) {
$hash = sha1(serialize($slip));
if(!in_array($hash, $hashes)) {
++$uniques;
$hashes[] = $hash;
}
}
var_dump($uniques); // prints total number of unique objects.
Edit:
#biakaveron's idea looks better though and could be adapted to:
$uniques = count(array_unique($array, SORT_REGULAR));
var_dump($uniques); // prints total number of unique objects.
This previous question has various solutions for removing duplicate arrays from within an array. If you implement any of them and then use sizeof() on the returned array you will have your solution.
eg:
<?php
$yourarray = array();
$tmp = array ();
foreach ($yourarray as $row)
if (!in_array($row,$tmp)) array_push($tmp,$row);
echo sizeof($tmp);
?>

Categories