After solving part of my problem over here, I realized that I could get the data into the view, but then I had another problem.
(controller)
$this->load->model('testing/test_v_to_m_model');
$data['mydata'] = $this->test_v_to_m_model->display_character_info();
$this->load->view('testing/test_v_to_m_view', $data);
(model)
$query = $this->doctrine->em->createQuery("select u from ORM\Dynasties2\Characters u");
return $query->getResult();
(view)
foreach ($mydata as $key => $row) {
print_r($row);
}
This returns output like so:
ORM\Dynasties2\Characters Object ( [id:ORM\Dynasties2\Characters:private] => 76 [name:ORM\Dynasties2\Characters:private] => Gwayn [whichFamily:ORM\Dynasties2\Characters:private] => 12 [bornDate:ORM\Dynasties2\Characters:private] => -467 [deathDate:ORM\Dynasties2\Characters:private] => -6 [marriedTo:ORM\Dynasties2\Characters:private] => 77 [marriedDate:ORM\Dynasties2\Characters:private] => -304 [marriageCode:ORM\Dynasties2\Characters:private] => [religion:ORM\Dynasties2\Characters:private] => 0 [isFemale:ORM\Dynasties2\Characters:private] => 0 [betrothedTo:ORM\Dynasties2\Characters:private] => [fathersId:ORM\Dynasties2\Characters:private] => 0 [successionOrder:ORM\Dynasties2\Characters:private] => 0 [isPregnant:ORM\Dynasties2\Characters:private] => [pregnantTurnsLeft:ORM\Dynasties2\Characters:private] => [marriedOutOfFamily:ORM\Dynasties2\Characters:private] => [bornMatrilineal:ORM\Dynasties2\Characters:private] => )
And so... I just don't know how to do anything with this- I tried a nested foreach to echo data and couldn't get it to work. I expect that its because this is an Object, not an Array, is that correct?
How exactly can I access/manipulate these fields?
Is there different code that I can use in my Doctrine2/CodeIgniter2 model that will give the data easier field names - like the equivalent to sql AS?
You should be able to access the object with pointers, like so:
foreach ($mydata as $key => $row) {
echo($row->id);
echo($row->name);
}
stdClass is php's generic empty class. Here is a nice tutorial on using this: http://krisjordan.com/dynamic-properties-in-php-with-stdclass
Edit:
Try using an accessor:
echo($row->getId());
Related
I am using phpredis in my application and I have the following data structure. The account Id acts as the key for each user:
$data = array(
"accId1"=> array("userId" => "user0234", "username" => "apples", "appversion" => "1.0"),
"accId2"=> array("userId" => "user2342", "username" => "roses", "appversion" => "2.0")
....
);
To store the above in the Redis I use pipelines like so:
$pipeline = $redis->multi(Redis::PIPELINE);
foreach ($data as $accId => $userInfo) {
$pipeline->hMSet($accId, $userInfo);
}
$pipeline->exec();
For retrieval:
$accIdSet = getAccountIds();
$pipeline = $redis->multi(Redis::PIPELINE);
foreach ($accIdSet as $accId) {
$pipeline->hMGet($accId, array("userId", "username", "appversion"));
}
return $pipeline->exec();
This returns the following array:
(
[0] => Array
(
[userId] => user0234
[username] => apples
[appverion] => 1.0
)
[1] => Array
(
[userId] => user2342
[username] => roses
[appversion] => 2.0
)
)
This is all good, except for the index of the array. The system I am working on requires the indexes to be the actual key stored in the Redis instead of a numerical index which it currently has.
Now I know I can iterate this array and use some PHP to change the index to the actual key, but before going there, I would like to know if I have a much more efficient and cleaner option to solve this problem.
I am open to any suggestion even if it changes the functions I use to interact with the Redis. Thank you!
I also encountered this problem, it seems can be resovle by redis itself directly. Maybe this is a workaround:
$data = $pipeline->exec();
foreach($data as $k => $v) {
$data[$k]['accId1'] = $accIdSet[$k];
}
return $data;
I am trying to return pull a value based on an attribute from an array, and it seems straight forward enough but I can't seem to nail down the correct way to accomplish this.
Here is the array I am trying to pull from:
[1] => InfoOptions Object
(
[description] => INFO
[optSequence] => 2
[eqpObject] => CUSTOMER NTWK ENG
[attribute] =>
[eqpValue] =>
[dlrSequence] => 10
)
[2] => InfoOptions Object
(
[description] =>
[optSequence] => 3
[eqpObject] => CUSTOMER TEST
[attribute] => CUSTOMER
[eqpValue] => Jon Doe
[dlrSequence] => 10
)
Here is what I have so far:
if (is_array($provisionCVResult->path->infoOptions-_InfoOptions)) {
foreach ($provisionCVResult->path->infoOptions ->InfoOptions as $cv_obj) {
$CVA = array();
$result = null;
foreach ($CV_obj as $value) {
if($value['attribute'] == 'CUSTOMER') {
$CVA["eqpValue"] = $cv_obj->eqpValue;
break;
}
}
$this->cvArrayDataList[] = $CVA;
}
}
Where am I going wrong?
If $provisionCVResult->path->InfoOptions is an array, it does not make sense to write $provisionCVResult->path->InfoOptions ->InfoOptions in the foreach
EDIT: I red in the comments that the array is $provisionCVResult->path->InfoOptions->InfoOptions
PHP is case sensitive so $cv_obj and $CV_obj are two different variables
The second foreach is not needed
So, assuming $provisionCVResult->path->InfoOptions->InfoOptions is returning an array of InfoOptions Object, I think you should do something like this:
if (is_array($provisionCVResult->path->InfoOptions->InfoOptions))
{
$result = null;
foreach($provisionCVResult->path->InfoOptions->InfoOptions as $cv_obj)
{
if($cv_obj->attribute == 'CUSTOMER')
{
$this->cvArrayDataList[] = array("eqpValue" => $cv_obj->eqpValue);
}
}
}
Having a quick look, try changing
$value['attribute'] == 'CUSTOMER'
To
$value->attribute == 'CUSTOMER'
As the element is an "InfoOptions object" and not an array.
Note I would also recommend using strict comparison, e.g '===' instead of '=='.
can someone tell me what is this code doing, As im new to Yii, learning about it.. im not able to understand few things.. Here is the code..
$allmsg = LogMsg::model()->findAll($criteria); //
$dataArr = array();
if (isset($allMsg) && sizeof($allMsg) != 0):
foreach ($allMsg as $msg) {
$dataArr[$msg->date][] = array( // array?
'category' => $msg->category, // what is that 'category' a variable or something else? and $msg->category, is what?
'time' => $msg->time,
'date' => $msg->date,
'user' => $msg->name
);
} endif;
$this->render('index', array(
'data' => $dataArr ) //what is that 'data'?
);
My question is, what is this line of code doing exactly in foreach loop
$dataArr[$msg->date][] = array(
'category' => $msg->category,
and here is second code... which has something like that..
$allCat = Categories::model()->findAll($criteria);
$catArr=array();
if(isset($allCat) && sizeof($allCat)!=0):
foreach ($allCat as $catModel) {
$catArr[$catModel->id] =$catModel;
}
endif;
return $catArr;
so what is this line doing in this code in foreach loop, what is different between these two lines in first and second code..
$catArr[$catModel->id] =$catModel;
last thing.. what is it
public static function getID($category)
{
$arr = array(
'ast'=>1, // what are these things? from where are they coming? db?
'fp'=>5, //
'per'=>3,
'ts'=>6,
'lg'=>3
);
return isset($arr[$category])?$arr[$category]:null; //Ternary - Condensed if/else statement
}
So as per your first question.
$dataArr[$msg->date][] = array(
'category' => $msg->category,
$allMsg is the active record object which u get through the db query. This object is traversed in a loop and each row is "$msg".
Hence you can access the attributes of the model through the $msg->category. 'category' here is the attribute of the model.
this is creating multidimensional array.
Your first question
$dataArr[$msg->date][] = array(
'category' => $msg->category,
will generate output like
[2016-03-04] => Array
(
[0] => Array
(
[category] => abc
)
)
And your second question
$catArr[$catModel->id] =$catModel;
will genrate output like
array(
[0] =>1,
[1] => 2,
[2] => 3,
)
Not tested.
I think, your question is not about Yii. You should read about arrays of PHP first. In the code multidimensional array have been used. It means that the array can contain another array as value.
I'm about ready to go crazy with this one. I can't seem to figure out how to print out elements of an array and then put all the results on one line (with a specific output).
Here's my array data (after running it through a foreach statement:
Array
(
[hostname] => server01
[server_id] => 4
[disk_mountpoint] => /
[disk_datetime] => 1426395600
[disk_device] => /dev/mapper/VolGroup00-LogVol00
[disk_capacity] => 15G
[disk_used] => 5.3G
)
Array
(
[hostname] => server01
[server_id] => 4
[disk_mountpoint] => /var
[disk_datetime] => 1426395600
[disk_device] => /dev/mapper/VolGroup01-LogVol00
[disk_capacity] => 107G
[disk_used] => 52G
)
Array
(
[hostname] => server01
[server_id] => 4
[disk_mountpoint] => /opt
[disk_datetime] => 1426395600
[disk_device] => /dev/mapper/VolGroup02-LogVol00
[disk_capacity] => 156G
[disk_used] => 127G
)
Here's my foreach statement:
foreach ($storage_report as $item) {
print_r($item);
}
I've spent a couple of hours trying to wrap my mind around a multi-dementional array as well as looking at some other peoples questions on StackOverflow, but nothing seems to fit what I'm trying to do.
By the way, the array above is actually output from a MySQL query and it returns only one unique hostname, so where it has the same hostname as an element, that is correct (same with the server_id).
I even tried a nested foreach loop and that didn't work well and I got confused again, so I didn't want to post it here.
Basically, with the data above, I want the output to look like:
$disk_mountpoint = $disk_used
With that being said, the ultimate output (if you were to parse what I just wrote), the final output would look like:
/ = 5.3G
/var = 52G
/opt = 127G
I feel like I'm over complicating things and wanted to know if someone could just point me in the right direction and help me out.
Thanks!
Drew
um.. just:
foreach ($storage_report as $item) {
echo $item['disk_mountpoint'] .'='.$item['disk_used'];
}
Yeah man over complication. Can't you just do
foreach ($storage_report as $item) {
echo $item['disk_mountpoint']."=".$item['disk_used'];
}
If it is that I undestand, so:
foreach ($storage_report as $item)
{
if (isset($item['disk_mountpoint']) && isset($item['disk_used']))
{
echo $item['disk_mountpoint'] .'='. $item['disk_used'];
}
}
That will iterate the entire collection and will read the content of each cell only if it is set.
I would like to have a simple a method, that can give back PHP Activerecord results as simple/associative arrays, not an array of ActiveRecord Objects.
In Ruby I believe this is done perhaps with .map() method. (I am not a Ruby guy...)
What I want is a simple method call, like toArray() in Zend_DB_Table, not a foreach, or something like that, but I can't seem to find it in their docs.
In PHP ActiveRecord getting a result is really easy:
$settings = SystemSettings::all();
But it gives back something like this:
[0] => SystemSettings Object
(
[errors] =>
[attributes:ActiveRecord\Model:private] => Array
(
[param] => author
[value] => Hawle
)
[__dirty:ActiveRecord\Model:private] => Array
(
)
[__readonly:ActiveRecord\Model:private] =>
[__relationships:ActiveRecord\Model:private] => Array
(
)
[__new_record:ActiveRecord\Model:private] =>
)
[1] => SystemSettings Object
(
[errors] =>
[attributes:ActiveRecord\Model:private] => Array
(
[param] => base_url
[value] => example.com
)
[__dirty:ActiveRecord\Model:private] => Array
(
)
[__readonly:ActiveRecord\Model:private] =>
[__relationships:ActiveRecord\Model:private] => Array
(
)
[__new_record:ActiveRecord\Model:private] =>
)
While this is really great in many cases, here, I would just like to have a simple array, like this:
Array
(
[author] => Hawle
[base_url] => example.com
)
I had a similar issue hopefully this can help someone else who stumbles on it. Obviously, this is specific to phpactiverecord.org.
In /lib/Model.php I added the following function:
public function to_array(array $options=array())
{
return $this->serialize('array', $options);
}
In /lib/Serialization.php I added the following class
class arraySerializer extends Serialization
{
public static $include_root = false;
public function to_s()
{
return self::$include_root ? array(strtolower(get_class($this->model)) => $this->to_a()) : $this->to_a();
}
}
I can then call ->to_array() and get an array back.
Hope this helps!
I was searching for the answer to this question in order to produce an array of results that could be easily json-encoded and sent as the response to an ajax call. I wanted only the attributes of each object in the array of results.
Unfortunately, you can't just call to_json() on each result and then json-encode the entire thing; you end up with double-encoding. Fortunately, though, the function and class posted by #willwashburn to solve this problem have now been included in php-activerecord, though they don't seem to have made it into the online documentation.
To return an array of results, do the following:
$data = MyModel::find('all');
foreach ($data as &$result) {
$result = $result->to_array();
}
Your entire result set will now be an array of arrays, containing only the attributes of each object. You can then do something like
echo(json_encode($data));
if you want to send it as the response to an ajax call.
This is my solution:
$posts = Post::find('all');
$arrayResult = array_map(function($res){
return $res->attributes();
}, $posts);
printf('<pre>%s</pre>', print_r($arrayResult, true));
class MyPHPActiveRecord extends PHPActiveRecord {
public function toJSON() {
return json_encode(get_object_vars($this));
}
}
You could do it like this:
funciton ar2array($settings){
$arr = array();
foreach($settings as $fieldObj){
$fieldName = $fieldObj->attributes["param"];
$fieldValue = $fieldObj->attributes["value"];
$arr[$fieldName] = $fieldValue;
}
return $arr;
}
$resultAsYouWant = ar2array($settings);
Hope this helps. Cheers
PS: If ->attributes is private use its accesor method (there must be one) as ->getAttributes() or equivalent.
I found this looking for solution of the same problem that I encountered using Yii framework - there is simplier way to do this in Yii.
$posts = Posts::model()->findAll();
foreach($posts as $result)
{
print_r($result->attributes);
}
It prints simple array as requested:
Array
(
[id] => 1
[title] => Title
[text] => Text
)
Hope it helps somebody.
My solution:
Added the following method to the utils class found in lib\Utils.php
public static function results_to_json($data)
{
$arr = array();
if(count($data)>0){
foreach($data as $row){
array_push($arr, $row->to_array());
}
}
return json_encode($arr);
}
Call by:
echo \ActiveRecord\Utils::results_to_json($dataobject);
Obviously this is no longer relevant to the OP; however, considering that it still took me over an hour to find a solution for this (no thanks to php-activerecords docs), this may help someone else.
$r = Model::find('$id')->attributes();
$a = [];
foreach ($r as $k => $v)
{
$a[$k] = $v;
}
Perhaps not the most elegant, but works perfectly.