开发者

A Simple PHP Array Manipulation

how would you turn this array:

array(
      0 => Title1,
      1 => Title2,
      3 => Address1,
      4 => Address2,
    )

to this array:

 array (
   0 => array(
    'title' => 'Title1'
    'address' =>'Address1'
   ),
   1 => array(
    'title' => 'Title2',
     'address' => 'Address2'
   )
 );

when you were initially given

$_POST['title'] = array('Title1', 'Title2');
$_POST['address'] = array('Address1', 'Address2');

which whe开发者_开发知识库n merged would give you the first array I have given

I was able to solve this via a high level Arr:Rotate function in Kohana framework, along with Arr::merge function but I can't quite understand the implementation. Please help


What about something like this :

$_POST['title'] = array('Title1', 'Title2');
$_POST['address'] = array('Address1', 'Address2');

$result = array();
$length = count($_POST['title']);

for ($i=0 ; $i<$length ; $i++) {
    $result[$i]['title'] = $_POST['title'][$i];
    $result[$i]['address'] = $_POST['address'][$i];
}

var_dump($result);

Which gives you the following result :

array
  0 => 
    array
      'title' => string 'Title1' (length=6)
      'address' => string 'Address1' (length=8)
  1 => 
    array
      'title' => string 'Title2' (length=6)
      'address' => string 'Address2' (length=8)

i.e. loop over both the title and address arrays you were initially given, and push their content into a new array -- without merging them or anything.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜