0

How can I turn this array:

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

into 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 when 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.

0

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Chunk, transpose, and assigned predefined keys. Demo

$array = [
      0 => 'Title1',
      1 => 'Title2',
      3 => 'Address1',
      4 => 'Address2',
];
    
var_export(
    array_map(
        fn($title, $address) => get_defined_vars(),
        ...array_chunk($array, 2)
    )
);

or with $_POST data: Demo

var_export(
    array_map(
        fn($title, $address) => get_defined_vars(),
        $_POST['title'],
        $_POST['address']
    )
);

Output (from either):

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.