I have following code in my controller:
$model=ChForms::model()->findByPk($id);
$decode= $model->json;
$res=CJSON::decode($decode);
var_dump($res);
return $this->render('index', array('model'=>$model, 'res'=>$res));
the result of var_dump($res) is:
["p_2"]=> string(4) "test" ["p_3"]=> string(1) "0"
How can I call values of ["p_2"] and ["p_3"] in my view(e.g test, 0)
CJSON::decode() returns an array by default. Since you are passing $res into your view you can access the required fields via $res["p_2"] and $res["p_3"].
Related
I have a returned string result from an API and it looks like this.. for the life of me, I cannot retried the WorkID value!
The returned string is a json string:
{"notes":"","RecordsStatus":"{\"0\":{\"WorkID\":\"0090210\",\"Message\":\"Record Created\"}}"}
It has two parts:
“notes” and “RecordStatus”.
If message is empty, means the batch is imported without error.
In RecordStatus, there are two parts too.
First is the index number of the record, and it has second part that the key for the record created(in my case it’s the WorkID) and a message tells the record is created or updated(in my case, it’s created).
Array
(
[notes] =>
[RecordsStatus] => {"0":{"WorkID":"0090210","Message":"Record Created"}}
)
Do a Var_dump() of decoded_json results in this:
array(2) {
["notes"]=>
string(0) ""
["RecordsStatus"]=>
string(52) "{"0":{"WorkID":"0090210","Message":"Record Created"}}"
}
I tried
foreach($decoded_json as $item) {
$uses = $item['RecordsStatus'][0]['WorkID']; //etc
}
but does not work
I have been trying to solve this problem for a long time already. I tried searching for an answer in stackoverflow, google and other sources but I didn't manage to find something that could lead me to the solution of the problem. I really hope you can help me. Thanks in advance.
Im using Codeigniter 3
My query in codeigniter is as shown here bellow:
$this->db->select($fields)
->from("usuario as u")
->join("usuario_info as ui ", "ui.idusuario = u.idusuario","left");
$this->db->where("usua_url",$this->url_usuario);
return $this->db->get(); //last line
I do get results from the query with data from a record which has an id (in the database is a PK and can't be NULL
My compiled query from CI is:
SELECT * FROM `usuario` as `u` LEFT JOIN `usuario_info` as `ui` ON `ui`.`idusuario` = `u`.`idusuario` WHERE `usua_url` = 'heri'
And my result is the following after applying result_array method (I censored some field names and its values, you know..):
array(9) {
["idusuario"]=> NULL
["other_field1"]=> string(9) "censored"
["other_field2"]=> string(60) "censored"
["other_field3"]=> string(26) "censored"
["other_field4"]=> string(19) "censored"
`["other_field5"]=> string(7) "censored"
["other_field6"]=> string(4) "censored"
["other_field7"]=> NULL
["other_field"]=> NULL
}`
When I copy and paste exactly the same query into DataGrip or Workbench I get the same results except for idusuario, the results look like:
array(9) {
["idusuario"]=> 1
["other_field1"]=> string(9) "censored"
["other_field2"]=> string(60) "censored"
["other_field3"]=> string(26) "censored"
["other_field4"]=> string(19) "censored"
`["other_field5"]=> string(7) "censored"
["other_field6"]=> string(4) "censored"
["other_field7"]=> NULL
["other_field"]=> NULL
}`
Well after trying something I thought wouldn't make any difference I got to the solution.
I had a method like for the query like this:
public function selectPerfilInfo($fields = "*"){
$this->db->select($fields);
$this->db->from("usuario as u");
$this->db->join("usuario_info as ui ", "ui.idusuario = u.idusuario","left");
$this->db->where("usua_url",$this->url_usuario);
return $this->db->get();
}
I was calling it like this in my controller:
//before calling the method I already set the `url_usuario` attribute of my class
$this->my_controller->selectPerfilInfo();
I changed the line above to this:
$this->my_controller->selectPerfilInfo("u.idusuario, u.other_field1");
After passing the specific fields to the function it returns the right results.
Im not sure why it happens and this leaves me a lot of doubts because I have used the same structure for getting records from other tables with no problems.
I'd appreciate if any of you could give me any information about it. Thanks
I have a request with Kohana which returns an array, just like this :
$query = DB::select()
->from('environnement')
->where('utilisateur_id','=', 'd83fa9a71cc1c414011cc1dbeb270026')
->where('region_id','=', $region_selectionnee);
$id_env = $query->execute();
return $id_env->as_array();
I call the request in my controller and var_dump the result. I get :
array(1) {
[0]=> array(4) {
["id"]=> string(32) "d83fa9a71cc1c414011cc1de74270027"
["courant"]=> string(1) "0"
["region_id"]=> string(1) "1"
["utilisateur_id"]=> string(32) "d83fa9a71cc1c414011cc1dbeb270026"
}
}
Now, I want to get the id field of this array, but I don't know how to do. I tried with $id_environnement->id but it says
Trying to get property of non-object
I also tried with $id_environnement["id"], but it says :
Undefined index: id
Can somebody help me to get this id please ? Thanks in advance !
As you can see, the result is an array, in which is the object you want. So you have to use $id_environment[0]["id"] to get it.
Arr::path($id_environment, '0.id')
This method don't raise exception if array key not exists
You can also use:
$id = DB::select('id')
->from('environnement')
->where('utilisateur_id','=', 'd83fa9a71cc1c414011cc1dbeb270026')
->where('region_id','=', $region_selectionnee)
->limit(1)
->execute()
->get('id', false);
Where the second argument in get() is what you want returned if 'id' is not found (if you don't include a second argument, it will return null if 'id' is not found).
edit
You don't have to specify 'id' within select(), but if you do specify a field (or fields), get() can only retrieve from the specified field(s).
I'm working on a project in CodeIgniter 2 and now I'm stuck on the most basic of concepts.
Model:
Get an object array from my table which contains all rows that match a specific value for a field named foo. There can be one or more rows that match. In this example, two rows.
public function get_sample($foo)
{
$query = $this->db->get_where('sample_db', array('foo' => $foo));
return $query->result();
}
Controller:
Assign the results and make output available to view.
public function view($foo)
{
$data['array'] = $this->sample_model->get_sample($foo);
$this->load->view('view', $data);
}
View:
echo var_dump($array); // for testing
echo $array[1]->text
var_dump() of $array:
array(2) {
[0]=> object(stdClass)#23 (4) {
["id"]=> string(1) "1"
["foo"]=> string(3) "bar"
["number"]=> string(4) "1234"
["text"]=> string(23) "This is content in 1234"
}
[1]=> object(stdClass)#24 (4) {
["id"]=> string(1) "2"
["foo"]=> string(3) "bar"
["number"]=> string(4) "9999"
["text"]=> string(23) "This is content in 9999"
}
}
The rendered ouput of echo $array[1]->text; is: This is content in 9999
And I understand how all that is working: $array[1]->text is the content of the text field in the array object with the index of 1, my second object.
However, I have a field called number and I want to access the object with a certain number and get its corresponding text value.
Example: How can I retrieve the value of text where the number is 9999? I cannot use $array[1]->text since I can never be sure of the object's position in the array. Something like $array['number' => '9999']->text, but I know that's not right. Maybe I need to loop through the array looking for a match?
This looks so simple yet everything I've tried has failed and resulted in various PHP errors. I've been studying the PHP manual here and here, but cannot seem to find anything about what I'm looking to do, or maybe I'm just misapplying what I'm reading. Any guidance is appreciated.
In addition to an answer using best practices following the MVC model, I'm hoping for a link to the proper page in the documentation, as well as pointing out any errors in my wording/terminology above.
EDIT:
This answer contains the actual code I used to solve my problem. Although, Yagi's answer was accepted because it put me in the right direction.
How about using this :
foreach ($array as $row) {
if ($row->number == '9999') {
echo $row->text;
}
}
Loop through the array, and find the number object value of 9999 and get the text
Why don't you just to a query and search for that number (or order by that number?)
Either way, what you need is a multidimensional array search function (that iterates through array of object and returns the found field value combo )
Something like this (put this in helper)
function multi_array_search($array, $field, $value)
{
$results = array();
if (is_array($array))
{
if ($array->$field == $value) //chek the filed against teh value, you can do addional check s(i.e. if field has been set)
$results[] = $array;
foreach ($array as $subarray)
$results = array_merge($results, multi_array_search($subarray, $key, $value)); //recurisve serach
}
return $results;
}
//than in view or in controller, depending where you need it
$result = multi_array_search($array, "number", "9999");
var_dump($result) will return or whether number of foudn instances
array() {
[0]=> object(stdClass)#24 (4) {
["id"]=> string(1) "2"
["foo"]=> string(3) "bar"
["number"]=> string(4) "9999"
["text"]=> string(23) "This is content in 9999"
}
}
you might be looking for something like this...
array_filter($array, function($o){ return $o->number == 9999; } );
http://php.net/manual/en/function.array-filter.php
EDIT
$o is the parameter in the callback function. each element of the array is passed to the callback function. if the function returns false, the element will be filtered out.
$arr = array(
(object) array(
'num' => 33,
'text' => 'hello',
),
(object) array(
'num' => 44,
'text' => 'world',
),
);
$filtered = array_filter($arr, function($o){ return $o->num == 33; });
echo $filtered[0]->text; // hello
as you stated, index will remain, so use array_values or array_shift. here's an example with function
function get_by_num($arr, $num){
return array_shift(array_filter($arr, function($o) use ($num) { return $o->num == $num; }));
}
$obj = get_by_num($arr, 44);
var_dump($obj);
// object(stdClass)#2 (2) { ["num"]=> int(44) ["text"]=> string(5) "world" }
in this case $obj will be either NULL if element is not found, or the first match. $num is transferred along so you can use any value. you can even improve it:
function get_first_match($arr, $field, $val){
return array_shift(array_filter($arr, function($o) use ($field, $val) { return $o->{$field} == $val; }));
}
$obj = get_first_match($arr, 'num', 44);
and now you can search any field. in your case
$obj = get_first_match($array, 'number', 9999);
Thanks to Yagi's answer, I came up with the following very simple solution. I loop through the array and assign the value of text to a new array with an index that matches the value of number. Then in the view file, I can access the text value based on this index.
Controller:
public function view($foo)
{
$data['array'] = $this->sample_model->get_sample($foo);
foreach ($data['array'] as $row) {
$data['result'][$row->number] = $row->text;
};
$this->load->view('view', $data);
}
View:
if (isset($result[9999])) echo $result[9999];
I have a problem when I want to query table using ORM ,example I have article table with field id,author,text.
My code like this :
// Single where
$article = Model_Article::find()->where('id', 4);
print_r($article);
that't code will be fetch all field on table article, it's like select * from article where id = 4
Try Possibility
$article = Model_Article::find(null, array('id','title'))->where('id', 3);
the response is
object(Orm\Query)#89 (14) {
["model":protected]=>
string(10) "Model_Article"
["connection":protected]=>
NULL
["view":protected]=>
NULL
["alias":protected]=>
string(2) "t0"
["relations":protected]=>
array(0) {
}
["joins":protected]=>
array(0) {
}
["select":protected]=>
array(1) {
["t0_c0"]=>
string(5) "t0.id"
}
["limit":protected]=>
NULL
["offset":protected]=>
NULL
["rows_limit":protected]=>
NULL
["rows_offset":protected]=>
NULL
["where":protected]=>
array(1) {
[0]=>
array(2) {
[0]=>
string(9) "and_where"
[1]=>
array(3) {
[0]=>
string(5) "t0.id"
[1]=>
string(1) "="
[2]=>
int(3)
}
}
}
["order_by":protected]=>
array(0) {
}
["values":protected]=>
array(0) {
}
}
that's is not return id or title field.
but when i'm try by adding get_one() method
$article = Model_Article::find(null, array('id','title'))->where('id', 3)->get_one();
id is return , but title is not and another field, i don't know why ?
Reference
ORM Discussion FuelPHP it's say ORM currently will be select all column, no plans to change that at the moment.
My Problem
Select Custom Field using ORM like this select id,owner from article where id = 4 it's will be return only id & owner, Is Possible to get that using ORM on FUELPHP ?
Do not use
Model_Article::find()->
but use
Model_Article::query()->
The first one works but is considered an error situation which might change in future versions.
As of version 1.4 the ORM supports partial selects, using
Model::query()->select('id', 'value')->
The second parameter of find() is an array of conditions for the find, such as 'where' or 'order_by' clauses. There is no support for selecting column names in this array.
The Orm\Model fetches all column because it can't deal with incomplete / partials objects.
If you want a custom query, don't use the ORM, use the query builder for that.
DB::select('id','title')->from(Model_Article::table())->where('id', 4);
if you are trying to find out result like query "select * from article where id = 4"
$article = Model_Article::find()->where('id', 4)->get_one();
print_r($article);
and one more concept you should understand
get_one() returns only one record (as a object ).
get() returns multiple record ( in the form of array of objects ).
and if your field is not displaying then check the model Model_Article .this problem may be occur when you have not declared fields in properties list.
Fuelphp has been release new version , you can see this documentation , in my case fuelphp version is 1.2 and cannot select custom field using orm.
select custom field using orm is available since version 1.4
http://fuelphp.com/docs/packages/orm/crud.html
// Find only some columns
Model_Article::query()->select('id', 'name');
Model_Article::find('all', array('select' => array('id', 'name')));