Detect how many array exist? - php

I am using CodeIgniter framework. I am sending an array to my view, but I could not get the array in my view.
This is my controller code:
public function edit($id)
{
$record = $this->Start_model->get_entry($id);//receiving array from model
$this->load->view('edit',$record);//send array to my view
}
This is my array on controller that I send:
Array
(
[0] => Array
( [id] => 1 [name] => Hamza [age] => 20 [address] => audit and account [phone] => 03000000000 )
)
But when I call this array view I get this error:
Undefined variable: record
This is how I am getting my array in view:
<?php
echo '<pre>';
print_r($record);
echo '</pre>';
?>
Now I know I am sending an array to my view but I want to know If there is array in my view or not. I can get record through another method but I think it is not a good practice. So anyone can help me how I can detect if there is an array in my view?

In your controller, send a parent array instead:
public function edit($id)
{
$data = array();
$data['record'] = $this->Start_model->get_entry($id); // provided this is not empty
$this->load->view('edit', $data);
}
Then in your view:
foreach($record[0] as $key => $value) {
echo $value['id'];
// the rest blah blah
}

Codeigniter extracts the array passed to a view, creating variables based on the keys of the array. To work as you want, pass an array with a key or record and a value of your array:
public function edit($id)
{
$data = array('record' => $this->Start_model->get_entry($id));
$this->load->view('edit',$data);//send array to my view
}
Then this will work in your view:
<?php
echo '<pre>';
print_r($record);
echo '</pre>';
?>
The way you are currently sending the data, it will be extracted into individual variables for each element in the array, however as your array is numerically indexed, and php variable name rules prevent numeric variable names, you cannot access the data.

Related

Accumulate strings and array values into an array as a class property via method

I have a class with method add() that accepts strings and arrays. I need to have an array with all users, but I cannot seem to get it. All I get is multiple arrays with all users. How could I merge those arrays into one?
class Users {
function add($stringOrArray) {
$arr = array();
if(is_array($stringOrArray)) {
$arr = $stringOrArray;
} else if(is_string($stringOrArray)) {
$arr[] = $stringOrArray;
} else {
echo('errrrror');
}
print_r($arr);
}
When I use this test:
public function testOne() {
$users = new Users();
$users->add('Terrell Irving');
$users->add('Magdalen Sara Tanner');
$users->add('Chad Niles');
$users->add(['Mervin Spearing', 'Dean Willoughby', 'David Prescott']);
This is what I get, multiple arrays but I need one array.
Array
(
[0] => Terrell Irving
)
Array
(
[0] => Magdalen Sara Tanner
)
Array
(
[0] => Chad Niles
)
Array
(
[0] => Mervin Spearing
[1] => Dean Willoughby
[2] => David Prescott
)
You can cut a lot of unnecessary bloat from your method.
You can cast ALL incoming data to array type explicitly. This will convert a string into an array containing a single element. If the variable is already an array, nothing will change about the value.
Use the spread operator (...) to perform a variadic push into the class property.
Code: (Demo)
class Users
{
public $listOfUsers = [];
function add($stringOrArray): void
{
array_push($this->listOfUsers, ...(array)$stringOrArray);
}
}
$users = new Users;
$users->add('Terrell Irving');
$users->add(['Magdalen Sara Tanner', 'Chad Niles']);
$users->add(['Mervin Spearing']);
var_export($users->listOfUsers);
Output:
array (
0 => 'Terrell Irving',
1 => 'Magdalen Sara Tanner',
2 => 'Chad Niles',
3 => 'Mervin Spearing',
)
All you need is to store the added users in a class property, for example $listOfUsers.
If adding the array you use the array_merge() function otherwise just add new user at the end of indexed array.
<?php
class Users {
// here will be all the users stored
public $listOfUsers = array();
function add($stringOrArray) {
//$arr = array();
if(is_array($stringOrArray)) {
// merge two arrays - could create duplicate records
$this->listOfUsers = array_merge($this->listOfUsers, $stringOrArray);
} else if(is_string($stringOrArray)) {
// simply add new item into the array
$this->listOfUsers[] = $stringOrArray;
} else {
echo('errrrror');
}
print_r($this->listOfUsers);
}
}
In your example you are storing the data locally within the method add() and it is not kept for future usage. This behavior is corrected using the class property $listOfUsers that can be accesed using $this->listOfUsers within the class object and if needed outside of the class.

How can I convert the array to a string variable in php codeigniter?

I am new to Codeigniter and want to display my state_name which I believe in an array, but I want the first element in that array to be in a variable and be displayed
I am getting the output as: Array ( [0] => stdClass Object ( [state_name] => XYZ state ) )
the output I want is just XYZ state
My controller goes like this:
public function downloadd()
{
$this->load->model('New_model');
$state_id=$this->input->post('state'); //gets me state_id from my view
$state_name = $this->New_model->getStatename($state_id); //gets me state_name in form of above output
print_r($state_name[0]);
exit;
}
And here is my model code:
public function getStatename($state_id) {
$this->db->select('state_name');
$this->db->where('state_id',$state_id);
$state_name=$this->db->get('states')->result();
return $state_name; //geting users data from db in result array
}
Please tell me where am I going wrong, Thanks for any contribution in advance :)
Just edit your last two lines of code in your model as follows:
$ans= $this->db->get('states')->row_array();
return $ans['state_name'];
This shall do the needful.
The result value is a array so you should use row_array to get first row and check if it exists:
public function getStatename($state_id) {
$this->db->select('state_name');
$this->db->where('state_id',$state_id);
$row = $this->db->get('states')->row_array();
if($row)
return $row['state_name'];
else {
//should handle the error since data not found
}
}

Can't pass variable from controller to view in CodeIgniter

I am having a problem trying to pass a variable from the controller to the view. I think I am doing a mistake somewhere, I can't find it since I am new to it.
My controller Method is :
public function paymentdetail($order_code)
{
$this->load->model('Payment_Model');
$paymentDetail = $this->Payment_Model->getpaymentdetail($order_code);
$orderDetail = $this->Payment_Model->getOrderDetail($order_code);
// echo print_r($paymentDetail);
$datas['content'] = $this->load->view('payment/paymentDetail',
array('paymentDetail' => $paymentDetail,
'orderDetail' => $orderDetail), true);
$this->load->view('layouts/main_template', $datas);
}
The following model function getpaymentdetail() returns an array (result_array()) and this is the one I am concerned about. If I can work this one out then I can also work with other model methods.
$this->Payment_Model->getpaymentdetail($order_code);
When I type <?php echo $paymentDetail['column_name']; ?> in view file(PaymentDetail.php) I get an error
Undefined index: column_name
Why do I get this error?
model function getpaymentdetail() returns an array (result_array())
those arrays are normally structured like this:
Array
(
[0] => Array
(
[ID] => 3120
[column_name] => col1
)
)
hence you cannot access column_name via <?php echo $paymentDetail['column_name']; ?> as this index doesn't exist in your array structure.
if you move one index deeper, then it will work: <?php echo $paymentDetail[0]['column_name']; ?>
Attention, if you expect more than 1 row to be returned, above will only access the first result (indexed 0) row! You'd need a foreach loop to get all results, see Generating Query Results - result arrays

Cannot use object of type stdClass as array when looping with array

I'm trying to get Count of a table called TestRunList that has the foreign key the same as another table called Testrun meaning i want to get count of how many testrunlist that single testrun has in the same page i did a forloop to get testrun id for each testrunlist but it didn't seem to work i get this error
Cannot use object of type stdClass as array
heres my Code in the controller
$data = DB::table('TestRun')->get();
$runs=array();
for ($i=0;$i<sizeof($data);$i++)
{
$testrunID=$data[$i]['TestRunID'];
$Testrunlist=TestRunList::where('test_run_id',$testrunID)->count();
$runs[$i]=[
'Countruns'=>$Testrunlist
];
}
return view('management.testrun.testrun-list')
->with('data',$data)
->with('runs', $runs);
$data is a Collection, you can't access using array syntax
$data = DB::table('TestRun')->get();
$runs = [];
$data->each(function ($row) use ($runs) {
$runs[] = [
'Countruns' => TestRunList::where('test_run_id',$row-> TestRunID)->count()
];
});
return view('management.testrun.testrun-list')
->with('data',$data)
->with('runs', $runs);
Always use
print_r($data);
if it's object run echo $data->username if array run echo $data['username'];
So you know what type of data you're dealing with.

PHP - adding an object with its properties to array

I have a problem with modifying an array.
foreach ($page->getResults() as $lineItem) {
print_r($lineItem->getTargeting()->getGeoTargeting()->getExcludedLocations());
}
This code gives a result:
Array
(
[0] => Google\AdsApi\Dfp\v201611\Location Object
(
[id:protected] => 2250
[type:protected] => COUNTRY
[canonicalParentId:protected] =>
[displayName:protected] => France
)
)
I'm trying to add another, [1] , same type of object to this array.
I made a class to create and add an object:
class Location{
public function createProperty($propertyName, $propertyValue){
$this->{$propertyName} = $propertyValue;
}
}
$location = new Location();
$location->createProperty('id', '2792');
$location->createProperty('type', 'COUNTRY');
$location->createProperty('canonicalParentId', '');
$location->createProperty('displayName', 'Turkey');
array_push($lineItem->getTargeting()->getGeoTargeting()->getExcludedLocations(), $location);
Then, if I pass this into print_r() function
print_r($lineItem->getTargeting()->getGeoTargeting()->getExcludedLocations());
It shows the same result.
In the end, I need to send this updated whole $lineItem to this function
$lineItems = $lineItemService->updateLineItems(array($lineItem));
But seems like before sending I can't properly add an object to the array.
Thanks in advance.
PHP returns arrays as a value instead of as a reference. This means you must set the modified value back somehow.
Looking at the library apparently in question, there seems to be setExcludedLocations method for that purpose.
So your code should be something like:
$geo_targeting = $lineItem->getTargeting()->getGeoTargeting();
$excluded_locations = $geo_targeting->getExcludedLocations();
array_push($excluded_locations, $location);
$geo_targeting->setExcludedLocations($excluded_locations);

Categories