如何使用PHP将普通数组转换为关联数组

时间:2018-08-03 12:50:59

标签: php arrays

我有一个字符串:<!DOCTYPE html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> </head> <body> <div class="container"> <div class="col-xs-6"> <div class="col-xs-12 col-sm-6"> <div class="col-xs-12">A</div> <div class="col-xs-12">E</div> <div class="col-xs-12">I</div> <div class="col-xs-12">M</div> </div> <div class="col-xs-12 col-sm-6"> <div class="col-xs-12">B</div> <div class="col-xs-12">F</div> <div class="col-xs-12">J</div> <div class="col-xs-12">N</div> </div> </div> <div class="col-xs-6"> <div class="col-xs-12 col-sm-6"> <div class="col-xs-12">C</div> <div class="col-xs-12">G</div> <div class="col-xs-12">K</div> <div class="col-xs-12">O</div> </div> <div class="col-xs-12 col-sm-6"> <div class="col-xs-12">D</div> <div class="col-xs-12">H</div> <div class="col-xs-12">L</div> <div class="col-xs-12">P</div> </div> </div> </div> </body> </html>

基本上我想拥有这种结构-

position1, position2

到目前为止,我已经尝试过了。

array(
    array('position' => 'position 1'),
    array('position' => 'position 2')
)

$positions = explode(',', "position1, position2"); $modPoses = []; foreach($positions as $pose): $modPoses['position'] = $pose; endforeach; print_r($modPoses);

Output:

如何获得所需的(如上所述)数组结构? 谢谢。

2 个答案:

答案 0 :(得分:2)

将两个值分配给同一索引没有任何意义,但是让我给您一个解决方案。如果您使用2d关联数组,则可以通过这种方式完成

$counter = 0; //initialize counter here
foreach($positions as $pose):
        $modPoses[$counter]['position'] = $pose;
        $counter++;
     endforeach;

答案 1 :(得分:1)

我想你想要的是

array(
    array('position' => 'position 1'),
    array('position' => 'position 2')
)

如果是这样,您可以使用:

array_map(function ($i) { return array('position' => $i); }, explode(',', 'position 1, position 2'))