I would like to step through a PHP array and create a variable for each entry in it. My array ($array) looks like this:
我想通过一个PHP数组来创建一个变量。我的数组($array)是这样的:
Array
(
[0] => Array
(
[first_name] => Arthur
[last_name] => Dent
[planet] => Earth
)
[1] => Array
(
[first_name] => Ford
[last_name] => Prefect
[planet] => Betelgeuse
)
)
I have got the following:
我有以下几点:
$0_first_name = $array['0']['first_name'];
$0_last_name = $array['0']['last_name'];
But this is pretty time consuming, and means I need to explicitly declare each one and then can't allow for extra entries within the array at each level.
但是这是非常耗时的,并且意味着我需要显式地声明每一个,然后不能允许在每个级别的数组中添加额外的条目。
I would like to know what is the best way of doing this please.
我想知道做这件事的最好方法是什么。
Thanks for the help
谢谢你的帮助
Mike
迈克
1 个解决方案
#1
0
Something like this should do what I think you are trying to do.
像这样的事情应该做我认为你想做的事情。
$data=array(
array('first_name'=>'Arthur','last_name'=>'Dent','planet'=>'Earth'),
array('first_name'=>'Ford','last_name'=>'Prefect','planet'=>'Betelgeuse')
);
foreach( $data as $i => $arr ){
foreach( $arr as $key => $value ){
${$key.$i}=$value;
${$i.'_'.$key}=$value;
}
}
echo $first_name0, $first_name1, ${'0_first_name'};
Obviously I have the integer after the name but it's trivial to reverse them and have something like $0first_name
or $0_first_name
- but they need to be handled differently when outputting them - ${'1_first_name'}
etc - again, as has been pointed out - not the best approach for maintainability so now I'll go off and rethink all the bad decisions I have made in life.
显然我后的整数的名字但微不足道的逆转,有0 first_name或0美元_first_name——但他们需要处理不同的输出时- $ { ' 1 _first_name }等,正如已经指出的,而不是最好的方法,可维护性现在我将离开和重新考虑所有我所犯的错误的决定。
#1
0
Something like this should do what I think you are trying to do.
像这样的事情应该做我认为你想做的事情。
$data=array(
array('first_name'=>'Arthur','last_name'=>'Dent','planet'=>'Earth'),
array('first_name'=>'Ford','last_name'=>'Prefect','planet'=>'Betelgeuse')
);
foreach( $data as $i => $arr ){
foreach( $arr as $key => $value ){
${$key.$i}=$value;
${$i.'_'.$key}=$value;
}
}
echo $first_name0, $first_name1, ${'0_first_name'};
Obviously I have the integer after the name but it's trivial to reverse them and have something like $0first_name
or $0_first_name
- but they need to be handled differently when outputting them - ${'1_first_name'}
etc - again, as has been pointed out - not the best approach for maintainability so now I'll go off and rethink all the bad decisions I have made in life.
显然我后的整数的名字但微不足道的逆转,有0 first_name或0美元_first_name——但他们需要处理不同的输出时- $ { ' 1 _first_name }等,正如已经指出的,而不是最好的方法,可维护性现在我将离开和重新考虑所有我所犯的错误的决定。