NEW Update
How will you write a array which output will be like this:
Array(1) { [0]=> object(stdClass)#29 (15) { ["cals"]=> string(11) "1545.616024" } }
OLD UPDATE
I am trying to manually insert value in a array if My db is resulting 0 results.
I am trying to create a manually a array which stores value as this model function stores
public function fetch_LifeStyeActivity_byid($activityDate, $uid) {
----
----
$query = $this->db->order_by('calorie_activity.ordering', 'ASC')->get_where('calorie_activity', array('creater_id' => $uid,'activity_date' => $activityDate, 'parent_id =' => '625'));
$data = array();
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
I am creating it like this from my controller like this
$data["lifeStyle_activity_query"] = array(
"cals" => "6"
);
$this->load->view('weight_lose/activities', $data);
& in view page while retrieving i am getting exception
foreach ($lifeStyle_activity_query as $row) {
echo $row->cals;
}
Exception getting as:
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Note: I only need help on modifying controller logic(please do not tell to change the view page code)
Your error simply comes from the fact that you've an array and try to use it as an object. You could just cast your array into an object so it can be used as such in your view.
$data["lifeStyle_activity_query"] = array(
"cals" => "6"
);
$data["lifeStyle_activity_query"] = (object) $data["lifeStyle_activity_query"];
echo $data["lifeStyle_activity_query"]->cals; // -> 6
Edit for your update :
$val['cals'] = '1545.616024';
$arr[0] = (object) $val;
Related
Hello There I need Help To Update on Vehicle Wies on Specific Dates.I'm Attaching Form image and Here is my Controller code.
public function add_vehicle_expense(Request $request)
{
$veh = array('veh_reg_num' => $request->veh_reg_num);
foreach ($veh as $data) {
print_r($request->date[$data]);
dd();
$veh = Sale_report::where('date',$request->date[$data])->where('veh_reg_num', $request->veh_reg_num[$data])->update(['diesel_qty'=> $request->qty[$data], 'diesel_rate'=> $request->rate[$data], 'diesel_amount'=> $request->total_amount[$data], 'other_expense'=> $request->other_exp[$data]]);
}
if ($veh) {
return redirect()->back()->with('Data Store Successfully');
}
//$veh = Sale_report::where('date',$request->date)->where('veh_reg_num', $request->veh_reg_num)->update(['diesel_qty'=> $request->qty, 'diesel_rate'=> $request->rate, 'diesel_amount'=> $request->total_amount, 'other_expense'=> $request->other_exp]);
/* foreach ($request->date as $reg_num => $key ) {
$s = Sale_report::where('date',$request->date[$reg_num])->where('veh_reg_num',$request->veh_reg_num[$reg_num])->first();
$s->diesel_qty = $request->qty[$reg_num];
$s->diesel_rate = $request->rate[$reg_num];
$s->diesel_amount = $request->total_amount[$reg_num];
$s->other_expense = $request->other_exp[$reg_num];
$s->update();
} */
}
I have try to Update Data by matching Each Vehicle Number with Date Some times it Show ErrorException Attempt to read property on int,ErrorException Undefined array key "data"
I have Found The Solution of this Problem.
I've use implode(',' , $request->veh_reg_num) Then I use $datas = explode() function then I use foreach() With exploded Vairable as foreach($datas as $data => $value){
match the each row that with $data array then I Update the values to data base }
I have one array that I am foreaching over:
array:8132 [
0 => {#551
"address_id": "94e224af-135f-af31-3619-535acfae9930"
"fiber_phase": "101"
"parsed_hash": "1bc7fb114ee10d7cb9cea10693d238b5"
"min_number": 400
"max_number": 499
"sales_rep": "164"
"id": "abd90d6b-28a8-2be6-d6c1-abd9007aef38"
"name": "48TH ST E"
"block_minimum": 400
"block_maximum": 498
}
Inside the foreach, I have another array, that I need to access certain properties for an if statement that will then add a new property to the original array ($data):
foreach ($data as $phase) {
$all_phases = EmeraldFiber::getPhases();
dd($all_phases);
if ($phase->fiber_phase === $all_phases[1]['name']) {
$phase->fiber_status = $all_phases[1]['fiber_status'];
}
return $data;
}
The dd($all_phases); looks like this:
array:270 [
1 => array:7 [
"id" => "10bc06d0-05de-07e2-b2de-5214fba5045a"
"name" => "1"
"description" => "50th France"
"encoded_points" => "_sbqGnesxPJwv#iJBKpv#fJ#"
"fiber_status" => "Live"
"status_date" => "2010-09-01 00:00:00"
]
With the above foreach, I am only getting the original array returned, without the new property fiber_status. Am I not returning it correctly? Or do I need to map over the second array ($all_phases) to access those properties properly?
I presume you don't need to return anything:
// receive object once instead receiving of it multiple times
$all_phases = EmeraldFiber::getPhases();
// extract required values
$phase_name = $all_phases[1]['name'];
$phase_status = $all_phases[1]['fiber_status'];
foreach ($data as $phase) {
if ($phase->fiber_phase === $phase_name) {
$phase->fiber_status = $phase_status;
}
}
// if you have this code in a function - return data here
// otherwise - you don't need return
// return $data;
Update:
If $all_phases is array with all available phases and you need to check if $phase->fiber_phase is among them, then you should do the following:
// receive object once instead receiving of it multiple times
$all_phases = EmeraldFiber::getPhases();
// create pairs
$phase_names = [];
foreach ($all_phases as $item) {
$phase_names[$item['name']] = $item['fiber_status'];
}
foreach ($data as $phase) {
// check if `$phase->fiber_phase` exists in `$phase_names`
if (isset($phase_names[$phase->fiber_phase])) {
// if it does - add it's value to `$phase` object
$phase->fiber_status = $phase_names[$phase->fiber_phase];
}
}
For a given PHP object (loaded from CouchDB) $obj:
class stdClass#1 (3) {
public $_id =>
string(10) "nochecksum"
public $_rev =>
string(34) "1-4f734a24465bf7ba2de316fe87ffa0c1"
public $rooms =>
class stdClass#2 (1) {
public $kitchen =>
class stdClass#3 (1) {
public $ceilingFan =>
bool(false)
}
}
}
And for a given multidimensional array of data $arr, consisting of changed or new values for properties:
array(1) {
'rooms' =>
array(1) {
'kitchen' =>
array(1) {
'needsCleaning' =>
bool(true)
}
}
}
How is it possible to set $obj's properties to be values from $arr?
The solution is simple for a single dimension array:
foreach ($arr as $k=>$v) {
$obj->{$k}=$v;
}
I tried with a recursive function, but I don't know how to reference the parent(s):
$obj = setObjectFromArray($obj, $arr);
function setObjectFromArray($obj, $arr, $tree=Array())
{
foreach ($arr as $k=>$v) {
if (is_array($v)) {
$tree[]=$k;
$obj = setObjectFromArray($obj, $v, $tree);
} else {
// Here $tree is Array('rooms','kitchen')
// I want to set $obj->rooms->kitchen->{$k}
}
}
return $obj;
}
I think passing a reference of the object's property to the recursive function might work - but I don't understand either enough to make an educated guess. Any help appreciated
You could do it like this:
function setObjectFromArray($obj, $arr) {
foreach ($arr as $k => $v) {
$obj->{$k} = is_array($v) ? setObjectFromArray($obj->{$k}, $v) : $v;
}
return $obj;
}
The major difference with your code is the assignment to $obj->{$k} instead of $obj: that way you rewrite (or create) the property at each level of the recursion tree.
Be aware that even if you call the function like this:
$result = setObjectFromArray($obj, $arr);
... $obj will still have been modified and be equal to $result.
This solution is not totally obvious and maybe can fail somewhere but still - it's pair of json functions:
$r = array(
'rooms' => array(
'kitchen' => array(
'needsCleaning' => true
)
)
);
echo '<pre>',print_r(json_decode(json_encode($r))), '</pre>';
Explanation: you encode array to json-string and then decode this string to object.
Maybe you can expand this code further.
I am VERY new to PhP. Quick question that I am having trouble finding the answer to online, although I am sure most of you will quickly know the answer. I have the following code creating an associative array and then I am trying to display it in a table. I know there are easier ways to display it in a table like a foreach loop, but I would like to learn this method first :
class CarDealer extends Company {
var $navbar_array = array();
function create_navbar_array ( ) {
$mainurl = $this->company_url; // get the main url address of this web page
$this->navbar_array = array( "Home Page"=>"$mainurl?whichpage=home", "Sales"=>"$mainurl?whichpage=sales",
"Support" => "$mainurl?whichpage=support", "Contacts" => "$mainurl?whichpage=contact" );
}
function getLeftNavBar() {
$data ="<table border='1' style='background-color:yellow; width:35%'>";
$data .="<tr><td>$this->navbar_array['Home Page']</td></tr>";
$data .="<tr><td>$this->navbar_array['Sales']</td></tr>";
$data .="<tr><td>$this->navbar_array['Support']</td></tr>";
$data .="<tr><td>$this->navbar_array['Contacts']</td></tr>";
$data .="</table>";
return $data;
}
}
Later in my code I create an object for my class and then try to print the table. Unfortunately I am just getting an output of things like Array['Home Page'].
$carobject = new CarDealer();
$carobject->create_navbar_array();
print $carobject->getLeftNavBar();
you need to pass array values to the function try
class extends Company {
var $navbar_array = array();
function create_navbar_array ( ) {
$mainurl = $this->company_url; // get the main url address of this web page
$this->navbar_array = array( "Home Page"=>"$mainurl?whichpage=home", "Sales"=>"$mainurl?whichpage=sales",
"Support" => "$mainurl?whichpage=support", "Contacts" => "$mainurl?whichpage=contact" );
return $this->navbar_array;
}
function getLeftNavBar($arr) {
$data ="<table border='1' style='background-color:yellow; width:35%'>";
$data .="<tr><td>".$arr['Home Page']."</td></tr>";
$data .="<tr><td>".$arr['Sales']."</td></tr>";
$data .="<tr><td>".$arr['Support']."</td></tr>";
$data .="<tr><td>".$arr['Contacts']."</td></tr>";
$data .="</table>";
return $data;
}
}
$carobject = new CarDealer();
$arr = $carobject->create_navbar_array();
print $carobject->getLeftNavBar($arr);
or need to make public your array
public $navbar_array = array();
before return $data;, print_r($data); so you can know the associative array's structure. If it didnt print on the page, try looking in view-page-source. You'll get an clear picture. I think $data should be an array, so prob it should be like
$data['someField'] = $someValues;
And, Create or define the array before you use them.
You need to concatenate the array values inside the getLeftNavBar() method so php knows to parse them.
try
$data .="<tr><td>{ $this->navbar_array['Home Page'] }</td></tr>";
or
$data .="<tr><td>".$this->navbar_array['Sales']."</td></tr>";
Why not just call create_navbar_array() inside getLeftNavBar()
function getLeftNavBar() {
$this->create_navbar_array();
.....
You could rewrite it like this
class CarDealer {
private function getUrls() {
return array(
"Home Page" => "$this->company_url?whichpage=home",
"Sales" => "$this->company_url?whichpage=sales",
"Support" => "$this->company_url?whichpage=support",
"Contacts" => "$this->company_url?whichpage=contact"
);
}
public function getLeftNavBar() {
$data ="<table border='1' style='background-color:yellow; width:35%'>";
foreach($this->getUrls() as $url ) {
$data .="<tr><td>".$url."</td></tr>";
}
return $data . "</table>";
}
}
$carobject = new CarDealer();
print $carobject->getLeftNavBar();
I have a multidimensional array that I want to access and change one of the values from an integer to a string using a helper function. The code below works but if I remove the if statement which I dont really need it gives me a Undefined index error on the helper code
$stories = multidimensional array in this format
array(1) {
[0]=> array(4)
{
["code"]=> string(1) "2"
["user_name"]=> string(4) "Dave"
["name"]=> string(11) "project one"
["sample_id"]=> string(1) "2"
}
}
to access the array I am using
foreach($stories as $key => $subarray) {
if(array_key_exists('code', $subarray)){
//if($stories[$key]['code'] > 0){
$stories[$key]['code'] = task_priority_text($stories[$key]['code']);
//};
}
}
Commenting the code in this way throws the error while uncommenting gives a clean result.
Here is the helper function which I have used elsewhere and works well
if ( ! function_exists('task_priority_text'))
{
function task_priority_text($priority = FALSE)
{
$options = array('0' => 'Urgent', '1' => 'High', '2' => 'Medium', '3' => 'Low', '4' => 'Minimal');
if($priority !== FALSE)
return $options[$priority];
else
return $options;
}
}
How do I get ride of this if statement?
EDIT
here is the error
A PHP Error was encountered
Severity: Notice
Message: Undefined index: Medium
Filename: helpers/tasks_helper.php
Line Number: 70
line 70 of the helper is
return $options[$priority];
You are looping over each item in the array multiple times. The 'outer' loop runs once for every item in the array, then the 'inner' loop (which someone else pointed out is redundant) runs again for every item in the $subarray variable.
foreach($stories as $key => $subarray) {
foreach($subarray as $subkey => $subsubarray) {
if(array_key_exists('code', $subarray)){
//if($stories[$key]['code'] > 0){
$stories[$key]['code'] = task_priority_text($stories[$key]['code']);
//};
}
}
}
This would be a better way of doing it:
foreach($stories as $story)
{
$story['code'] = task_priority_text($story['code']);
}