PHP - Splitting array (name and value) into different strings?
I have the following array:
Array
(
[name] => hejsan
[lastname] => du
)
I'm trying to loop through every item in the array, and store the name of the item in the array, and the value of that item, in two seperate strings.
Something like this:
$name1 = "name";
$value1 = "hejsan开发者_运维知识库";
$name2 = "lastname";
$value2 = "du";
Is that possible?
Thanks in advance!
You can use a foreach to loop through the key=>value
pairs of an associative array:
foreach ($array as $key=> $value) {
// Set the strings here
}
However, have you considered how you're going to store these string values as variables? You will either need to use dynamically named variables, which are (imo) messy, or you will want to use two arrays to store the keys and values anyway. If you're just going to use two arrays, you may as well take advantage of PHP's inbuilt array functionality:
$array = // your associative array
$arrayKeys = array_keys($array); // the keys
$arrayValyes = array_values($array); // the values
So, with this, $name1
would be $arrayKeys[0]
, $value1
would be $arrayValues[0]
, and so on. Note that yes, this may (I don't know how array_keys
/array_values
are implemented) be less efficient than a single loop through, but unless your array is massive that is not going to be a problem at all.
Use foreach:
foreach ($array as $keyname => $data) {
// Do whatever
}
精彩评论