Reputation: 193
I am trying to merge the data in the arrays 'c' and 'a' inside MyData
with the following code, but recently found out that there is a function called Set::combine. How can I use the combine method in CakePHP 2? I searched for tutorials but can't find a decent one that can actually help me out with the solution. Some examples or tips will be great!
I want to merge [my_test]
and [my_date]
inside [MyData]
with Set::combine.
Array
(
[0] => Array
(
[MyData] => Array
(
[id] => 79
[my_birth_day] => 1990-06-20
[my_address] => 400
[my_age] => 26
[my_name] => Joy
[my_id] => 1
[created] => 2017-06-19 15:39:44
)
[c] => Array
(
[my_test] => math
)
[a] => Array
(
[my_date] => 2017-08-13
)
).....Loops
[1] => Array
(
I would want the result to be like this:
Array
(
[0] => Array
(
[MyData] => Array
(
[id] => 79
[my_birth_day] => 1990-06-20
[my_address] => 400
[my_age] => 26
[my_name] => Joy
[my_id] => 1
[created] => 2017-06-19 15:39:44
[my_test] => math
[my_date] => 2017-08-13
I wrote this code to merge the arrays and display it as the above code, but I want to use Set::combine the $res.
$res = $this->find( 'all', $cond); // All the data are fetchd from this $res
$count = count($res);
for($i=0;$i<$count;$i++){
$result[] = $res[$i] ;
$fixed_arrays[] = $result[$i]['MyData'];
if (!empty($result[$i]['c'])) {
$corrupt_c_array = $result[$i]['c'];
$fixed_arrays = array_merge($fixed_arrays,$corrupt_c_array);
}
if(!empty($result[$i]['a'])) {
$corrupt_a_array = $result[$i]['a'];
$fixed_arrays = array_merge($fixed_arrays, $corrupt_a_array);
}
}
$result['data'] = $fixed_arrays; // This $result['data'] should show the expected result.
Upvotes: 0
Views: 261
Reputation: 2011
You can't do what you are asking to do with Set::combine (or Hash::combine in later versions of CakePHP). It just doesn't work that way. However, you can simplify what you are currently doing with the following:
foreach($yourArray as $key => $data){
$yourArray[$key] = $data['MyData'] + $data['c'] + $data['a'];
}
This will output what you are looking for.
Array (
[0] => Array (
[MyData] => Array (
[id] => 79
[my_birth_day] => 1990-06-20
[my_address] => 400
[my_age] => 26
[my_name] => Joy
[my_id] => 1
[created] => 2017-06-19 15:39:44
[my_test] => math
[my_date] => 2017-08-13
)
)
)
Upvotes: 1
Reputation: 189
$result = Set::combine('', '{n}.MyData', '{n}.c', '{n}.a');
i hope this useful for you.
Upvotes: 1