Home >Backend Development >PHP Tutorial >php数组解决办法

php数组解决办法

WBOY
WBOYOriginal
2016-06-13 12:27:14922browse

php数组

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


如何用 $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吧
------解决思路----------------------
<br /><?php<br />$str=array();<br />$strarray = array(<br />	array('one'=>1,'two'=>2,'three'=>3),<br />	array('one'=>1,'two'=>2,'three'=>3),<br />	array('one'=>1,'two'=>2,'three'=>3),<br />);<br />foreach($strarray as $k=>$v){<br />	$str['one'][] = $v['one'];<br />	$str['two'][] = $v['two'];<br />	$str['three'][] = $v['three'];<br />}<br />print_r($str);<br />?><br />



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
        )

)

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:请问字符串拼接Next article:js里写php代码解决方法