当前位置:Gxlcms > PHP教程 > php数组解决办法

php数组解决办法

时间:2021-07-01 10:21:17 帮助过:20人阅读

php数组

.....

$str=array();
foreach($strarray as $k=>$v){
$one=$v['one'];
$two=$v['two'];
$tree=$v['tree'];

}



如何用 $str保存成如下
$str=array('one'=>$v['one'],'two'=>$v['two'], 'tree'=>$v['tree'])
------解决思路----------------------
$strarray是一个数组,$str是单个元素,不知道数组结构怎么映射成一个元素的
如果$str是多个元素的数组的话,可以这么写
$str=array();
foreach($strarray as $k=>$v){
$str[] = array(
'one' => $v['one'],
'two' => $v['two'],
'tree' => $v['tree'],
);
}

当然还有更简单的方法:
$str=array();
foreach($strarray as $k=>$v){
$str[] = array_intersect_key($v, array('one' => 1, 'two' => 1, 'tree' => 1));
}

还有不是tree,是three吧
------解决思路----------------------

$str=array();
$strarray = array(
array('one'=>1,'two'=>2,'three'=>3),
array('one'=>1,'two'=>2,'three'=>3),
array('one'=>1,'two'=>2,'three'=>3),
);
foreach($strarray as $k=>$v){
$str['one'][] = $v['one'];
$str['two'][] = $v['two'];
$str['three'][] = $v['three'];
}
print_r($str);
?>



Array
(
[one] => Array
(
[0] => 1
[1] => 1
[2] => 1
)

[two] => Array
(
[0] => 2
[1] => 2
[2] => 2
)

[thress] => Array
(
[0] => 3
[1] => 3
[2] => 3
)

)

人气教程排行