开发者

Create new variables from array keys in PHP

开发者 https://www.devze.com 2023-02-08 17:44 出处:网络
Suppose I have an array, like this: $foo = array(\'first\' =>\'1st\', \'second\' => \'2nd\', \'third\' =>\'3rd\');

Suppose I have an array, like this:

$foo = array('first' =>  '1st',
             'second' => '2nd',
             'third' =>  '3rd');

How can I pick the keys ou开发者_JAVA百科t of the array and make them their own variables? For example, the array $foo would become:

$first = '1st';
$second = '2nd';
$third = '3rd';

I ask this because I am creating an MVC framework to help with my OOP, and I would like the user to pass a variable to the View loading function, which will allow the user to use variables in the template without having to know what the array was called.

For example:

$array = array('title' =>  'My blog!' [...]);
$this->load->view('view.php', $array);

view.php:

echo $title;

Output:

My blog!


<?php extract($array); ?>

http://php.net/manual/en/function.extract.php


You could do this:

foreach($foo as $k => $v) {
  $$k = $v;
}


A simple method is to use variable variables:

foreach($foo as $key => $value) {
   $$key = $value;
}

echo $first; // '1st'

Note that this is generally discouraged however. It would be better to alter your templating system to allow for variables to be scoped within the template. Otherwise you could have issues with collisions and have to test for their existence, etc.


In PHP 7.1, you can use the list() and it's shorthand to create new variable from array keys.

$foo = array('first' =>  '1st',
             'second' => '2nd',
             'third' =>  '3rd');
list('first' => $first, 'second' => $second, 'third' => $third) = $foo;
// $first = '1st'

// or use shorthand
['first' => $first, 'second' => $second, 'third' => $third] = $foo;

This gives you more control on pulling out variables from an array. For instance, you can pull out only 'first' and 'second' and skip other.


This is really an answer to my own question, but since it was marked as a duplicate, I was advised to post my answer here. (I do not have the privilege to post in meta.)

When you have a table in a database with many columns, it can be an hassle to make a variable for each one. The great thing is that you can make variables automatically!

This method uses the heading / title / name of the columns in a database table as variable names, and the content of the selected row as the variables' value.

This approach is suitable when you only select one row from the table. My code with comments:

$query = "SELECT * FROM mdlm WHERE mdlmnr = $id";  // Select only *one* row, the column mdlmnr is a unique key
$resultat = $conn->query($query); //Get the result (the connection is established earlier)

while ($col = $resultat->fetch_field()) { //fetch information about the columns
    $kolonnetittel = $col->name; //Set the variable as the name of the column
    echo $kolonnetittel . "<br>"; //Show all the column names/variables
}

$innhold = $resultat->fetch_assoc(); // get the content of the selected row as an array (not a multidimensional array!) 
extract($innhold, EXTR_PREFIX_SAME, "wddx"); // Extract the array

Since I'm no pro the code might not be the best, but it works for me :-) When the list of the variables appeared on my web page I copied it into Excel and used concatenate to make php/html/css-code: paragraphs with designated class for each variable. Then I copied this code back into the code of my web page, and moved every piece around. Before finishing I commented out this line:

//echo $kolonnetittel . "<br>"; 

Useful links:

  • W3 School on fetch_field
  • PHP on fetch_field
  • PHP on Extract
  • W3 School on Extract
  • Video tutorial: Inserting database results into array in PHP

I hope this '"tutorial" might help someone else!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号