views:

108

answers:

5

how would you turn this array:

Array
(
    [0] => 234234234
    [1] => 657567567
    [2] => 234234234
    [3] => 5674332
)

into this:

Array
(
    [contacts] => Array(
            [0] => Array
             (
                            [number] => 234234234
                            [contact_status] => 2
                            [user_id] =>3 

                        )
            [1] => Array
             (
                            [number] => 657567567
                            [contact_status] => 2
                            [user_id] =>3
                        )
            [3] => Array
             (
                            [number] => 234234234
                            [contact_status] => 2
                            [user_id] =>3
                        )
            [4] => Array
             (
                            [number] => 5674332
                            [contact_status] => 2
                            [user_id] =>3
                        )
                )
)

is there a cakephp specific way how to transform this array?

thank you

+4  A: 

Try this:

$output = array('contacts'=>array());
foreach ($input as $val) {
    $output['contacts'][] = array(
        'number'         => $val,
        'contact_status' => 2,
        'user_id'        => 3
    );
}

I assume that contact_status and user_id are static since you didn’t tell anything else.

Gumbo
+2  A: 
$input = array(...);
$arr = array();
foreach ($input as $id) {
  $arr[] = array(
    'number' => $id,
    'contact_status' => 2,
    'userid' => 3;
  );
}
$output = array('contacts' => $arr);
cletus
It’s *contacts* and not *contents* ;-)
Gumbo
+5  A: 

nicer

$contact_status = 2;
$user_id = 1;
foreach($input as $number)
    $output['contacts'][] = compact('number', 'contact_status', 'user_id');
stereofrog
A: 

A little bit of cleanup from sterofrog's solution. Declare the array and use array_push instead of assigning it to an empty index.

$output = array( );
$contact_stats = 2;
$user_id = 3;
foreach( $input as $number ) {
    array_push( $output[ 'contact' ], compact(
        'number',
        'contact_status',
        'user_id'
    ));
}
Abba Bryant
what are the reasons?
ondrobaco
it uses array_push because ( someone correct me if I am wrong ) it is faster than assigning values to an empty index.Also, I think using array_push with compact is easier to read than the previous version. Declaring $output as an array ahead of time is simply good coding practice. It prevents php warnings and clearly indicates that output is an array.
Abba Bryant
A: 

Why are the resulting array keys 0, 1, 3, 4... ?

Symen Timmermans