array transformation in php - php

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

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);

Related

merge 2 array with different number of keys

I have 2 arrays
$arr1 = Array
(
[REG1] => 94
[REG3] => 45
)
$arr2 =Array
(
[0] => REG1
[1] => REG2
[2] => REG3
[3] => REG4
)
I have to loop 2 arrays and I would like a result in one array like this:
Array(
[0] => Array(
[REG1] => 94
)
[1] => Array(
[REG2] =>
)
[2] => Array(
[REG3] => 45
)
[3] => Array(
[REG4] =>
)
)
But for the instand I can not do what I want, here is where I am:
private function mergeData($arr1, $arr2){
$result = array_map(function($v1, $v2){
$t[$v1] = $v2;
return $t;
}, $arr2, $arr1);
return $result;
}
output:
Array(
[0] => Array(
[REG1] => 94
)
[1] => Array(
[REG2] =>45
)
[2] => Array(
[REG3] =>
)
[3] => Array(
[REG4] =>
)
)
I cannot correctly put the bone values with the right keys.
I tried with array_merge_recursive but also failed.
Thanks for your help
$arr3 = array_fill_keys( $arr2, '' );
creates an array containing the values of $arr2 as keys with as value an empty string.
$arr3 =Array
(
[REG1] => ''
[REG2] => ''
[REG3] => ''
[REG4] => ''
)
After that just merge.
$result = array_merge ( $arr3, $arr1 );
Another option would be to use the array_map function and map key with the corresponding values, if any:
$arr1 = [
'REG1' => 94,
'REG3' => 45
];
$arr2 = [
'REG1',
'REG2',
'REG3',
'REG4'
];
$result = array_map(function($item) use($arr1){
return [$item => isset($arr1[$item]) ? $arr1[$item] : ""];
},$arr2);
This will return:
Array
(
[0] => Array
(
[REG1] => 94
)
[1] => Array
(
[REG2] =>
)
[2] => Array
(
[REG3] => 45
)
[3] => Array
(
[REG4] =>
)
)
Using a loop:
<?php
$arr1 = [
'REG1' => 94,
'REG3' => 45
];
$arr2 = [
'REG1',
'REG2',
'REG3',
'REG4'
];
$result = $arr2;
foreach($result as &$v)
$v = [$v => $arr1[$v] ?? null];
unset($v);
var_export($result);
Output:
array (
0 =>
array (
'REG1' => 94,
),
1 =>
array (
'REG2' => NULL,
),
2 =>
array (
'REG3' => 45,
),
3 =>
array (
'REG4' => NULL,
),
)

Get sum of values which have same value for key php array

I have below array,
Array ( [0] => Array ( [report_id] => 1 [amount] => 100.00 [category_name] => Trial1 ) [1] => Array ( [report_id] => 1 [amount] => 150.00 [category_name] => Trial2 ) [2] => Array ( [report_id] => 1 [amount] => 200.00 [category_name] => Trial2 )
What i want to send to have JSON with below format
It will get some of Equal category name and then send it as json.
[{'category_name': 'Trial1', 'Sum':100]}, {'category_name':'Trial2', 'Sum':350]
How can i achieve this?
Was thinking to get foreach loop and then make compare of category_name and use .=+ to get sum? but i lost there,
Thanks,
Try below solution:
<?php
$array = array (
'0' => Array ( 'report_id' => 1, 'amount' => '100.00', 'category_name' => 'Trial1' ) ,
'1' => Array ( 'report_id' => 1, 'amount' => '150.00' ,'category_name' => 'Trial2' ),
'2' => Array ( 'report_id' => 1, 'amount' => '200.00' ,'category_name' => 'Trial2' ) ,
);
$new_array = array();
foreach($array as $a){
if(!isset($new_array[$a['category_name']]['amount'])){
$new_array[$a['category_name']]['amount'] = 0;
}
$new_array[$a['category_name']] = array(
'category_name' => $a['category_name'],
'amount' => $new_array[$a['category_name']]['amount'] + $a['amount'],
);
}
//print_r(array_values($new_array));
echo json_encode(array_values($new_array));
Output
[{"category_name":"Trial1","amount":100},{"category_name":"Trial2","amount":350}]
Possible solution:
$categoriesArray = array();
foreach ($yourArray as $arrayItem) {
if (!isset($categoriesArray[$arrayItem['category_name']])) {
$categoriesArray[$arrayItem['category_name']] = array(
'category_name' => $arrayItem['category_name'],
'sum' => 0
);
}
$categoriesArray[$arrayItem['category_name']]['sum'] += $arrayItem['amount'];
}
$categoriesArray = json_encode(array_values($categoriesArray));
Assuming $input is your array and $output is the JSON string:
$categorysum = [];
array_walk($input, function($el) use (&$categorysum) {
$categorysum += [$el['category_name'] => ['category_name' => $el['category_name'], 'Sum' => 0]];
$categorysum[$el['category_name']]['Sum'] += $el['amount'];
});
$output = json_encode(array_values($categorysum));

merge arrays where some value of parent arrays is not equals

I array of arrays, what look something like that:
$messages = array (
0 =>
array(
'keyT' => 'id.key'
'mess' => array(
array(1,0)
)
...
)
I want to merge mess preperties of arrays where 'keyT' is not equals.
I run trought the arrays:
foreach ($messages as $k => $current) {
foreach ($messages as $ke => $all) {
if ($current['keyT'] == $all['keyT']) {
array_merge( ... )
}
}
}
But this not deve me any results. Maybe somebody can help me. Thanks!
Try this code
$messages = array(
0 =>
array(
'keyT' => 'A',
'mess' => array(
array(1, 0)
)
),
1 =>
array(
'keyT' => 'A',
'mess' => array(
array(1, 2)
)
),
2 =>
array(
'keyT' => 'B',
'mess' => array(
array(3, 4)
)
)
);
$result = array();
foreach ($messages as $msg) {
$key = $msg['keyT'];
if (!isset($result[$key])) {
$result[$key] = array();
}
$result[$key] = array_merge($result[$key], $msg['mess']);
}
print_r($result);
Output
Array
(
[A] => Array
(
[0] => Array
(
[0] => 1
[1] => 0
)
[1] => Array
(
[0] => 1
[1] => 2
)
)
[B] => Array
(
[0] => Array
(
[0] => 3
[1] => 4
)
)
)

Move inner array values to parent array, reset keys and change key name to string

I have an array as such:
[0] => Array
(
[0] => 1
[1] => 30
[2] => 33
)
[1] => Array
(
[id] => 5
)
I want to move all values in the [0] index out so they become part of the parent array. So the final outcome would look like such:
[0] => Array
(
[id] => 1
)
[1] => Array
(
[id] => 30
)
[2] => Array
(
[id] => 33
)
[3] => Array
(
[id] => 5
)
As you can see the numerical indexes on [0] have now changed to id
I've tried using array_map('current', $array[0])
to no avail, any suggestions?
You could use the ol' trusty double foreach:
$new_array = array();
foreach ($array as $arr) {
foreach ($arr as $ar) {
$new_array[] = array('id'=>$ar);
}
}
Demo
$data = array(
array(1, 30, 33),
array('id' => 5)
);
$result = array();
array_walk_recursive(
$data,
function($value) use (&$result) {
$result[] = array('id' => $value);
}
);
var_dump($result);
Just to show that iterators can be really useful tools as well:
$data = array(
array(1, 30, 33),
array('id' => 5)
);
$result = array();
foreach (new RecursiveIteratorIterator(
new RecursiveArrayIterator($data),
RecursiveIteratorIterator::LEAVES_ONLY
) as $value) {
$result[] = array('id' => $value);
}
var_dump($result);
$array = [
[1, 30, 33],
['id' => 5]
];
$result = array_reduce($array, function (array $result, array $array) {
return array_merge($result, array_map(
function ($id) { return compact('id'); },
array_values($array)
));
}, []);
var_dump($result);
Admittedly not the simplest way to solve this, but very "functional". ;)
$array = array(
array(0 => 1,1 => 30,2 => 33,),
array("id" => 5,)
);
$result = array_merge(
array_map('array_flip',
array_chunk(
array_fill_keys($array[0], "id"),
1, true)
),
array_slice($array, 1)
);
var_export($result);
Results in:
array (
array ( 'id' => 1 ),
array ( 'id' => 30 ),
array ( 'id' => 33 ),
array ( 'id' => 5 )
)

Mix arrays together

I have this PHP array:
Array(
[0] => Array(
["Import"]=> Array
(
[0] => 1.00
[1] => 2.00
[2] => 1.00
[3] => 9.00
)
["Page"] => Array
(
[0] => 1
[1] => 4
[2] => 5
[3] => 6
)
["Key"] => Array
(
[0] => 1
[1] => 22
[2] => 88
[3] => 3
)
)
)
I need to get:
Array(
[0] => Array(
[0] => Array(
["Import"] => 1.00
["Page"] => 1
["Key"] => 1
)
[1] => Array(
["Import"] => 2.00
["Page"] => 4
["Key"] => 22
)
[2] => Array(
["Import"] => 1.00
["Page"] => 5
["Key"] => 88
)
[3] => Array(
["Import"] => 9.00
["Page"] => 6
["Key"] => 3
)
)
)
I've checked array_merge and array_combine but I can't find a way to use them in this case.
How can I do?
Try this. Seems to work as you expect.
<?php
$source = array(
array(
'Imports' => array(
1.00,2.00,1.00, 9.00),
'Page' => array(
1,4,5,6),
'Key' => array(
1,22,88,3)
)
);
print_r($source);
$dest = array();
foreach($source as $key => $src) {
foreach($src as $typeKey => $typeArr) {
foreach($typeArr as $index => $val){
$dest[$key][$index][$typeKey] = $val;
}
}
}
print_r($dest);
?>
Here is a demo: http://codepad.org/bht4ne7K
In PHP 5.5 you can easily achieve that with array_column() function:
$array = [
'Imports' => ['i0', 'i1'],
'Page' => ['p0', 'p1'],
'Key' => ['k0', 'k1']
];
$i = 0;
$result = array_map(function($x) use ($array, &$i)
{
return array_combine(array_keys($array), array_column($array, $i++));
}, current($array));
//var_dump($result);
-but for earlier versions you'll need to gather your array with foreach like:
$result = [];
foreach($array as $key=>$item)
{
foreach($item as $i=>$value)
{
$result[$i][$key] = $value;
}
}
//var_dump($result);
-you'll need, of course, do that with each element of your parent array (code above is a sample of how to rearrange 2-level array). That, again, can be easily done with array_map()
Something like this:
function switchKeys(Array $input) {
$result = array();
foreach ($input as $field => $data) {
if (is_array($data)) {
foreach ($data as $index => $value) {
$result[$index][$field] = $value;
}
}
}
return $result;
}
$input = array(
"imports" => array(1.00, 2.00, 1.00, 9.00,),
"page" => array(1, 4, 5, 6,),
"key" => array(1, 22, 88, 3,),
);
$output = switchKeys($input);
var_export($input);
var_export($output);
Note that your input array has one more level, so you should call the function for each sub array

Categories