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
开发者_JS百科 )
[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
nicer
$contact_status = 2;
$user_id = 1;
foreach($input as $number)
$output['contacts'][] = compact('number', 'contact_status', 'user_id');
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.
$input = array(...);
$arr = array();
foreach ($input as $id) {
$arr[] = array(
'number' => $id,
'contact_status' => 2,
'userid' => 3;
);
}
$output = array('contacts' => $arr);
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'
));
}
You can simply use the array_map function like this:
$result = array_map(function ($n){
return array(
'number' => $n,
'contact_status' => 2,
'user_id' => 3);
}, $original);
精彩评论