so,i have two variables $posts and $comments that holds the array of posts and comments respectively,i have a separate view that accepts these variables,executes a foreach loop and prints them on the same page. The question here is,how do i pass both the variables to a view?
If its a single variable i pass it like this $this->load->view('myview',$myvar).
I tried passing it as an array like this,but still it doesnt work.
$data=array($var1,$var2);
$this->load->view('myview',$data);
Any help would be greatly appreciated! Thanks.
You need to access the variable in your view as you pass it. Using array($var1,$var2); is valid but probably not what you wanted to achieve.
Try
$data = $var1 + $var2;
or
$data = array_merge($var1, $var2);
instead. See Views for detailed documentation how to access variables passed to a view.
The problem with using array($var1,$var2); is that you will create two view variables: ${0} and ${1} (the array's keys become the variable names, you have two keys in your array: 0 and 1).
Those variable names are invalid labels so you need to enclose the name with {} on the view level.
By that you loose the ability to name the variables usefully.
The easiest thing to do in your controller:
$data['posts'] = $posts;
$data['comments'] = $comments;
$this->load->view('your_view', $data);
Then, in your view you just simply do something like:
foreach($posts as $post) {
...
}
You can hold any object in the $data variable that you pass to your view. When I need to traverse through result sets that I get from my models I do it that way.
Using associative array looks the best possible solution.
take an array
$data = array(
'posts' => $posts,
'comments' => $comments,
);
$this->load->view('myview',$data);
Probably this will help you to get a solution.
this is another and recommended way using compact:
$data1 = 'your data';
$data2 = 123;
$data3 = array();
$this->load->view('myview', compact('data1', 'data2', 'data3');
try
$data1 = 'your data';
$data2 = 123;
$data3 = array();
$this->load->view('myview', $data1 + $data2 + $data3);
$this->render($views_array,$data);
Related
Alright, So I'm redoing my question so people can understand what I'm trying to do.
Search.php
<?php
$getItems = file_get_contents('Items.json');
if(isset($_GET['searchVal'])){
$getItems2 = json_decode($getItems, true);
$data2 = array("items" => array(array()));
foreach($getItems2['items'] as $data){
if(strpos($data['name'], $_GET['searchVal'])){
$data2 = array("items" => array(array($data)));
}
}
echo json_encode($data2,JSON_UNESCAPED_SLASHES);
} else{
echo $getItems;
}
Problem: Doesn't get all items which have that name, gets only one.
Search is done, now I have to fix somehow to get all items which match the name. How could I do that?
You have the following inside a loop:
$data2 = array(...)
...and then you reference $data2 outside the loop.
Of course, it will only contain the last entry, because that line is overwriting $data2 with new data each time the loop iterates.
If you want to keep all the records from the loop, use
$data2[] = array(...)
instead.
[EDIT]
Further guessing as to what you actually want your JSON to look like, I guess you want all the records to be in the items array?
So in that case, let's rewrite your $data2 line, as follows:
$data2['items'][] = array($data);
This will add all the data arrays to your items array in $data2. I will note that your array structure is really convoluted -- too many nested arrays, which makes it difficult to be sure I'm giving you the answer you want even now, but hopefully if it isn't exactly right, it will show you the direction you need to go.
You'll also want to have an additional line at the top of your code to initialise $data2, like this:
$data2 = array('items'=>array());
This should be somewhere at the top of the code, before $data2 is used, and outside of the loop.
I'm trying to run a sql query and return all values into an array of the tables names...
This is what I have so far:
$vehiclemodeldata = DB::table('model')->where('model_id', $viewData['model_id'])->get();
$row = $vehiclemodeldata->row();
foreach ($row as $key => $value){
$viewData['vehiclemodeldata_'.$key]= $value;
}
What are your throughts?
EDIT
I've tried this it seems to bring it back in an array but I can't access the array for some reason.
$VehicleModel = DB::table('model')->where('model_id', $viewData['model_id'])->get();
Thanks
This is because $vehiclemodeldata = DB::table('model')->where('model_id', $viewData['model_id'])->get(); actually returns an object instead of an array.
Your foreach loop is correct. You can later access properties in the array by using syntax like this $viewData['vehiclemodeldata_1']->yourProperty; which is used to access properties of objects.
Hope it answers the question.
$vehiclemodeldata = DB::table('model')->where('model_id', $viewData['model_id'])->first();
$viewData['vehiclemodeldata'] = $vehicle->toArray();
But why would you like to do this?
I would pass query result directly to view instead
$vehicle = DB::table('model')->where('model_id', $id)->first();
return View::make('whateverview', compact('vehicle'));
// view file
Model: {{ $vehicle->model }}
...
I've googled around and didn't see the answer. I have an array I'm storing in a variable that I'm trying to pass to a function..
$myArr = 'array('item1', 'item2')';
require('script.php'); //where actual function is
makeCode($myArr);
When I use makeCode(array('item1', 'item2')); it works fine.. I've even tried to add global $myArr to makeCode, but that didn't work either.
I'm thinking it's a scope problem, but maybe I'm misusing the string. print_r($myArr) prints properly, it just isn't passing or something.
The function basically just compares $myArr values and if it matches what's in the function's array, it outputs the correct HTML, so I didn't list it. It works, just not the variable.. Thanks!
--makeCode()--
function makeCode($listArr){
/* global $myArr; //Tried this */
$output = '';
$items = array(
'item1' => "Code for item1",
'item2' => "Code for item2"
)
/* $myArr = $listArr; //tried this too */
foreach ($listArr as $val) {
if(array_key_exists($val, $items)){
if(strlen($output)>0) $output .="|"; //Add Sytnax
$output .="$items[$val]";
}
}
}
That's pretty much it.
$myArr = 'array('item1', 'item2')';
$myArr is a string here. I'm not sure that's what you meant. Try:
$myArr = array('item1', 'item2');
If this is what you meant then this will behave differently than calling
makeCode(array('item1', 'item2'));
Because this is calling using an actual array.
I'm currently using the following format to save a value from an HTML form $item_name=$_POST['item_name'];
This saves the value, but how to I also save the name attribute in a variable?
Thanks in advance!
Assuming you want to store each element of $_POST variable as a key-value pair, then you can try:
$var = array();
foreach($_POST as $key => $val) {
$var[$key] = $val;
}
I'm saving a lot of values and want to avoid typing each one out.
Please, make your mind first.
Global variables are intended to be typed by hand.
If you want some automated processing - just keep them in a form of array.
Looks like rdt.exe's answer is what you're looking for.
maye you noticed you have to use the name to access the $_POST-array and get the value. if you want to store the name in a variable, too, just do:
$item_name_name = 'item_name';
$item_name_value = $_POST[$item_name_name];
you could also use some kind of loop to dynamically create variables with the according names like this:
foreach( $_POST as $name => $value ){
$$name = $value;
}
both ways are some kind of unnecessary and useless in my opinion, but you havn't stated what exactly you're trying to achive - so maybe this helps.
An alternative approach:
$keysarray = array_keys ( $_POST);
print_r( $keysarray);
This will give you all the keys in array
The function you are looking for is called extract.
This will create variables for all the $key=>$val pairs in the array.
$_EXAMPLE = array('bird' => 'chicken', 'dog' => 'greyhound');
export($_EXAMPLE);
echo $bird; # prints "chicken"
echo $dog; # prints "greyhound"
Watch out though - this is a huge security risk. So are the solutions described in some of the other answers.
The problem with doing something like this is that a user can tamper with the POST data, and set parameters other than the ones she is supposed to set. If they set variables that are actually variable names in your application, those variables can be overwritten.
$is_admin = false;
$_EXAMPLE = array('bird' => 'chicken', 'dog' => 'greyhound', 'is_admin' => 'true');
export($_EXAMPLE);
if ($is_admin) { # this will now evaluate to true.
# do sensitive stuff...
}
I have created two arrays. I wanna pass these two array to any function. I am beginner with function so tried with rough code to achieve my task. As I have some values in $cntctnum and $cntcttype named array.
$cntctnum = array();
$cntcttype = array();
$response = array();
function play_with_array($cntctnum, $cntcttype){
$contactnumber= $cntctnum[];
$cntcttype = $cntcttype[];
// some code to play with array.
return resultarray();
}
$response = play_with_array($cntctnum, $cntcttype);
Is this right way to pass function in array?
Is I need to declare $response as array before or when I return resultarray(), it will automatically consider it as array?
You don't need to define $response as array beforehand, but it might be a good idea to do so anyway depending on what the code afterwards expects.
In your function you don't return a function call resultarray() but a new array:
function play_with_array($cntctnum, $cntcttype) {
$contactNumber = $cntctnum; // You don't need the assignment! Note: No brackets here!
$resultArray = array();
// Do something here
return $resultArray;
}
You have:
$cntctnum = array();
$cntcttype = array();
$response = array();
function play_with_array($cntctnum, $cntcttype){
$contactnumber= $cntctnum[]; // don't need []
$cntcttype = $cntcttype[]; // don't need []
// some code to play with array.
return resultarray(); // this is a function?
}
$response = play_with_array($cntctnum, $cntcttype);
I would do something like this
$cntctnum = array();
$cntcttype = array();
function play_with_array($contactnumber, $cntcttype){
// some code to play with array.
$response = array($contactnumber,$cntcttype);
return $response;
}
$response = play_with_array($cntctnum, $cntcttype);
echo "<pre>".print_r($response,true)."</pre>";
Rahul, you pass array to a function just like you pass any other variable to a function. The reason to have a function is to have a block of code that can be re-used to perform the same set of calculations, etc.
It's hard to understand what you're trying to do inside your function. If this is something that's repeatable, meaning: compare array 1 vs array 2, get the bigger one, and return some sort of variation of that, then YES, create a function. If you have some code inside your function that is very specific to this page only and to these 2 arrays, you don't need the function. Just write the code inline.
Is I need to declare $response as array before or when I return resultarray(), it will automatically consider it as array?
No, you don't. If you resultarray variable inside a function is truly an array, you're good to go.