PHP has a function extract that will convert an array like this:
$array = array(
'var1' => 1,
'var2' => 2
);
to:
$var1 = 1;
$var2 = 2;
now, I need the opposite, i have few variables:
$var3 = 'test';
$test = 'another';
$datax = 1;
that needs to be:
$array = array(
'var3' => 'test',
'test' => 'another',
'datax' => 1
);
Is there something like this in PHP?
You can use compact() to achieve this.
$var3 = 'test';
$test = 'another';
$datax = 1;
$array = compact('var3', 'test', 'datax');
Reference: http://php.net/manual/en/function.compact.php
like this
$preDefined = (get_defined_vars());
$var3 = 'test';
$test = 'another';
$datax = "1";
$newDefined = array_diff(get_defined_vars(), $preDefined);
print_r($newDefined);
$array = get_defined_vars()
See get_defined_vars()
You'd have to be really sure you wanted to do this (it includes things in the global scope automatically) but you can use
$my_vars = get_defined_vars();
If you want it more selective than that, you could look at filtering it like this:
$my_vars = pack_vars(get_defined_vars())
function pack_vars ($defined_vars)
{
$packed = array();
$ignored = array('dont_use_this', 'ignored_var', 'ignore_this_too');
foreach ($defined_vars AS $key => $value)
{
if (!in_array($key, $ignored))
{
$packed[$key] = $value;
}
}
return $packed;
}
Related
I am having trouble getting my php script to work when using a function in if statements.
The code currently runs, but doesn't give me any information, nor any errors, if I remove the IF'S it works fine, but the project I am working on, this is essential.
Here is my code - I have took out the SQL to save space..
if ($VAR === 'PK%') {
CDB::UseDB('blah', 'blah', 'blah', 'blah');
$sql = "blah blah
";
$lrs = CDB::ExecuteQuery($sql);
if ($lrs) {
$jsonData = convert($lrs);
function convert($lrs)
{
// RE-GET VARIABLE AS IT CAN'T GET IT FROM OUTSIDE OF FUNCTION
$VAR = $_GET['VARIABLE'];
$intermediate = array();
while ($vals = CDB::GetAssoc($lrs)) {
$key = $vals['VAR'];
$y = $vals['MEASURE_1'];
if (!isset($intermediate[$key])) $intermediate[$key] = array();
$intermediate[$key][] = array('x' => count($intermediate[$key]), 'y' => $y);
}
$output = array();
foreach ($intermediate as $key => $values) {
$output[] = array(
"key" => $key,
'values' => $values
);
}
return json_encode($output, JSON_NUMERIC_CHECK);
}
}
}
Can anyone shed some light on what I am doing wrong?
You are defining your function in a conditional way. In that case its definition must be processed prior to being called.
I would recommend declaring your function separately and then use it, like:
function convert($lrs) {
// RE-GET VARIABLE AS IT CAN'T GET IT FROM OUTSIDE OF FUNCTION
$VAR = $_GET['VARIABLE'];
$intermediate = array();
while ($vals = CDB::GetAssoc($lrs)) {
$key = $vals['VAR'];
$y = $vals['MEASURE_1'];
if (!isset($intermediate[$key])) $intermediate[$key] = array();
$intermediate[$key][] = array('x' => count($intermediate[$key]), 'y' => $y);
}
$output = array();
foreach ($intermediate as $key => $values) {
$output[] = array(
"key" => $key,
'values' => $values
);
}
return json_encode($output, JSON_NUMERIC_CHECK);
}
if ($VAR === 'PK%') {
CDB::UseDB('blah', 'blah', 'blah', 'blah');
$sql = "blah blah";
$lrs = CDB::ExecuteQuery($sql);
if ($lrs) {
$jsonData = convert($lrs);
}
}
I'm passing a lot of parameters in a function
I want to know if its wrong what i am doing and if it is possible to put all those variables into an array and just call the array:
Here my function parameters:
function addjo($logo, $job_category, $job_name, $status, $localization, $job_type, $contract_type, $description)
My code to recognize all the variables.
if (isset($_POST['add_jo'])){
$job_category =$_POST['job_category'];
$description = $_POST['description'];
$job_name = $_POST['job_name'];
$logo = $_POST['logo'];
$status = $_POST['status'];
$localization = $_POST['localization'];
$job_type = $_POST['job_type'];
$contract_type = $_POST['contract_type'];
addjo($logo, $job_category, $job_name, $status, $localization, $job_type, $contract_type, $description);
}else{
$logo = NULL;
$job_category = NULL;
$job_name = NULL;
$status = NULL;
$localization = NULL;
$description = NULL;
$job_type = NULL;
$contract_type = NULL;
$check1 = NULL;
$check2 = NULL;
}
Is it possible to do something like this?
if(isset($_POST['mybutton'])){
array[](
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
);
function(callarrayhere);
else{
$var1 = null;
$var2 = null;
}
Thanks.
Since $_POST is already an array, just use it:
addjob($_POST);
And in addjob:
function addjob($input) {
// verify that array items are present and correct.
}
Exporting an array's values to individual variables is not only a waste of time and memory, but it also makes your code harder to read (where do these variables come from? It's not obvious they came from the same source array)
Of course it's possible:
if (isset($_POST['add_jo'])){
$a = array();
$a['job_category'] =$_POST['job_category'];
$a['description'] = $_POST['description'];
// and so on
$a['contract_type'] = $_POST['contract_type'];
addjo($a);
}
else
{
$a['job_category'] = null;
// and so on
}
And in function addjo you can display all values that way:
function addjo($a) {
foreach ($a as $k => $v) {
echo $k.' '.$v."<br />"
}
// or
echo $a['job_category'];
}
Yes it is possible to have an array as an argument to a function. Your syntax isn't quite right. This would do it:
function addjo($params){
echo $params['logo'];
echo $params['job_category'];
echo $params['job_name'];
}
Usage example:
$arr = array(
'logo' => $logo,
'job_category' => $job_category,
'job_name' => $job_name
);
addjo($arr);
You could also have default parameters for each of the array elements, or make them optional. See this answer for how to do that.
I got 2 arrays:
$ping_array = array();
$ping_array[] = '400';
$ping_array[] = '200';
$ping_array[] = '600';
$ping_array[] = '100';
$timestamp_array = array();
$timestamp_array[] = '2013-03-25 16:30:07';
$timestamp_array[] = '2013-03-25 16:30:39';
$timestamp_array[] = '2013-03-25 18:30:06';
$timestamp_array[] = '2013-03-25 18:45:49';
I want to make something like this (i dont know how its called):
$combined_array = array(
'time' => $timestamp_array,
'ping' => $ping_array
);
so later on i could use the 2 arrays combined like this:
foreach ($combined_array as $ca=> $values) {
echo $values['ping'];
echo $values['time'];
}
Thx guys this combine_array is amazing
Try this:
$combined_array = array();
foreach ($ping_array as $key => $value){
$combined_array[] = array(
'time' => $timestamp_array[$key],
'ping' => $value
);
}
What about this?
for ($i=0; $i<count($timestamp_array); $i++) {
$combined_array[$i]["ping"] = $ping_array[$i];
$combined_array[$i]["time"] = $timestamp_array[$i];
}
PHPs array_combine: "Creates an array by using one array for keys and another for its values"
$combined_array = array_combine($timestamp_array, $ping_array);
Then just repeat through similar to what you included:
foreach($combined_array as $time => $ping) {
echo $ping;
echo $time;
}
How about php 'array_merge_recursive'? It does exactly what you are looking for. It is found on php 4 and up.
What you could do is make array of objects, like this:
class PingInfo {
public $ping;
public $time;
public function PingInfo($ping, $time) {
$this->ping = $ping;
$this->time = $time;
}
}
$pingInfos = array();
$pingInfos[] = new PingInfo('400', '2013-03-25 16:30:07');
$pingInfos[] = new PingInfo('300', '2013-03-25 16:50:13');
You could build it from two array like this:
$pingInfos = array();
for ($i = 0; $i < count($ping_array); $i++)
$pingInfos[] = new PingInfo($ping_array[$i], $timestamp_array[$i]);
Now you can access it like this:
foreach ($pingInfos as $pingInfo) {
echo $pingInfo->ping;
echo $pingInfo->time;
}
Lets say that we have dynamically generated array.
$arr[1]["a"] = "value";
$arr[1]["b"] = "value";
$arr[1]["c"] = "value";
$arr[2]["a"] = "value";
$arr[2]["b"] = "value";
$arr[2]["c"] = "value";
$arr[2]["d"] = "value";
$arr[3]["a"] = "value";
$arr[3]["g"] = "value";
Generating the Array can be manipulated, so do not take this example like a core lines.
As you see there is different keys, but at the end we must get:
$arr[1]['a'] = 'value';
$arr[1]['b'] = 'value';
$arr[1]['c'] = 'value';
$arr[1]['d'] = 'empty value';
$arr[1]['g'] = 'empty value';
$arr[2]['a'] = 'value';
$arr[2]['b'] = 'value';
$arr[2]['c'] = 'value';
$arr[2]['d'] = 'value';
$arr[2]['g'] = 'empty value';
$arr[3]['a'] = 'value';
$arr[3]['b'] = 'empty value';
$arr[3]['c'] = 'empty value';
$arr[3]['d'] = 'empty value';
$arr[3]['g'] = 'value';
non empty values are different, so array_merge is not so using good idea.
I think you want this (this is horribly inefficient but my brain is struggling)
$keys = array();
foreach($arr as $array){
$keys = array_merge($keys, array_keys($array));
}
//$keys now has all unique keys
foreach($arr as $array){
foreach($keys as $key){
if(!isset($array[$key])){$array[$key] = null}
}
}
This is untested but i think it should work
I Guess is you want to fill your array with default values ... you can use array_fill to do that
$keys = array("a","b","c","d","g");
$arr[1] = array_combine($keys,array_fill(0, 5, 'empty value'));
$arr[1]["a"] = "value";
$arr[1]["b"] = "value";
$arr[1]["c"] = "value";
print_r($arr[1]);
Output
Array
(
[a] => value
[b] => value
[c] => value
[d] => empty value
[g] => empty value
)
Lets say I need three arrays, ford, chevy and dodge. Each array has three items:
$ford['engine'] = 'something';
$ford['color'] = 'something';
$ford['price'] = 'something';
$chevy['engine'] = 'something';
$chevy['color'] = 'something';
$chevy['price'] = 'something';
$dodge['engine'] = 'something';
$dodge['color'] = 'something';
$dodge['price'] = 'something';
I can write that out no problem and it doesn't take too long. But, lets say I need fifty or sixty arrays that I need to make, all with ten to twenty different items. I want to put a variable at the top of each array's file to denote what the array name will be, but I am not quite clear on the syntax and I am not too familiar with $$ or how I would use that with arrays:
$name = 'ford';
$(I want this to be "$name")['engine'] = 'something';
$(I want this to be "$name")['color'] = 'something';
$(I want this to be "$name")['price'] = 'something';
I have also considered just doing this:
$name = 'ford';
$view[$name.'_engine']
$view[$name.'_color']
$view[$name.'_price']
Can I get some suggestions on the best way to approach this?
Write a small function to do that
$cars = array(); //Create an array to hold the values
function writeArray($car, $var1, $var2, $var3) {
global $cars;
$cars[$car] = array('engine' => $var1, 'color' => $var2, 'price' => $var2);
}
//Now use it like
writeArray('Chevy', $something, $something, $something);
//If you want to access the array in the form of $ford['engine'] then use this
extract($cars); //This will split the array into small array accessible by model
You can use variable variables:
$var = 'ford';
$$var['engine'] = '...';
$$var['color'] = '...';
$var = 'chevy';
$$var['engine'] = '...';
$$var['color'] = '...';
Or just use multidimensional array:
$cars = array();
$make = 'ford';
$cars[$make] = array();
$cars[$make]['engine'] = '...';
$cars[$make]['color'] = '...';
// or
$cars['ford'] = array(
'engine' => '...',
'color' => '...',
);