Mix arrays together - php

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

Related

Grouping in array

I have following array..I am trying to group this.
Array
(
[0] => Array
(
[Title] => HoMedics MAN-300
[ean] => 31262006288
[upc] => 31262006288
[ProductImageName] =>
[CdnUri] =>
[ASIN] => B000050FEU
[ListPrice] => 129.99
[Status] => 2
[ActualPrice] => 129.99
[ProductID] => 5286728
)
)
I want to group this into
Array
(
[0] => Array
(
[VitalInfo]=>array(
[Title] => HoMedics MAN-300
[ean] => 31262006288
[upc] => 31262006288
[ProductImageName] =>
[CdnUri] =>
[ASIN] => B000050FEU
)
[Price]=>array(
[ListPrice] => 129.99
[Status] => 2
[ActualPrice] => 129.99
[ProductID] => 5286728
)
)
I tried but it doesn't happen as I want ...any help would be great...Thanx in advance..
try this,
CODE :
foreach($old_array as $key_old => $val_old)
{
foreach($val_old as $key => $val)
{
if(in_array($key, $VitalInfo_array))
{
$new_array[$key_old]['VitalInfo'][$key] = $val;
}
else
{
$new_array[$key_old]['Price'][$key] = $val;
}
}
}
OUTPUT :
Array
(
[0] => Array
(
[VitalInfo] => Array
(
[Title] => HoMedics MAN-300
[ean] => 31262006288
[upc] => 31262006288
[ProductImageName] =>
[CdnUri] =>
[ASIN] => B000050FEU
)
[Price] => Array
(
[ListPrice] => 129.99
[Status] => 2
[ActualPrice] => 129.99
[ProductID] => 5286728
)
)
)
DEMO
i hope it will be helpful.
Simply loop through your array and customize a new array accordingly.
Assuming $array is the original array, and $result is the customized array, try this:
foreach ($array as $k => $arr) {
$result[$k]['VitalInfo'] = array(
'Title' => $arr['Title'],
'ean' => $arr['ean'],
'upc' => $arr['upc'],
'ProductImageName' => $arr['ProductImageName'],
'CdnUri' => $arr['CdnUri'],
'ASIN' => $arr['ASIN']
);
$result[$k]['Price'] = array(
'ListPrice' => $arr['ListPrice'],
'Status' => $arr['Status'],
'ActualPrice' => $arr['ActualPrice'],
'ProductID' => $arr['ProductID']
);
}
Input : $info // Your Original Array
Ouput : $finalArr // Your Required Array
$vitalInfo = array ('Title','ean','upc','ProductImageName','CdnUri','ASIN');
$price = array ('ListPrice','Status','ActualPrice','ProductId');
$finalArr = array();
foreach ($info as $arr) {
$result = array();
foreach($arr as $k => $v){
if(in_array($k,$vitalInfo))
$result['VitalInfo'][$k] = $v;
else if(in_array($k,$price))
$result['Price'][$k] = $v;
}
$finalArr[] = $result;
}
If you are grouping this in php, have a look at these answers.
Or just copy this:
$input = [0 => [
'Title' => 'HoMedics MAN-300',
'ean' => 31262006288,
'upc' => 31262006288,
'ProductImageName' => '',
'CdnUri' => '',
'ASIN' => 'B000050FEU',
'ListPrice' => 129.99,
'Status' => 2,
'ActualPrice' => 129.99,
'ProductID' => 5286728
]];
foreach ($input as $in){
$out['VitalInfo'] = [];
$out['Price'] = [];
foreach ($in as $key => $i){
if (in_array($key, ['Title', 'ean', 'upc', 'ProductImageName', 'CdnUri', 'Asin'])){
$out['VitalInfo'][] = [$key => $i];
} else {
$out['Price'][] = [$key => $i];
}
}
$output[]=$out;
}
echo '<pre>';
var_dump($output);

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

Removing items from an array based on items in another array

I have 2 arrays:
Array ( [0] => Array ( [intTrackId] => 41 [intAverageRating] => 10 [bolNewRelease] => 0 [dtDateAdded] => 2013-03-08 17:32:26 ) [1] => Array ( [intTrackId] => 1 [intAverageRating] => 7 [bolNewRelease] => 0 [dtDateAdded] => 2013-03-08 18:54:35 ))
Array ( [0] => Array ( [intTrackId] => 41 [intAverageRating] => 5.5000 [bolNewRelease] => 1 [dtDateAdded] => 2014-03-25T09:39:28Q ) [1] => Array ( [intTrackId] => 361 [intAverageRating] => 8.0000 [bolNewRelease] => 1 [dtDateAdded] => 2014-03-25T09:39:28Q ))
I want to remove the items in the second which have a matching track ID in the first. So in this example, I would get:
Array ( [0] => Array ( [intTrackId] => 361 [intAverageRating] => 8.0000 [bolNewRelease] => 1 [dtDateAdded] => 2014-03-25T09:39:28Q ))
Is this possible with array_filter or is this a little complex for that?
Just use array_udiff() - it's intended to do this:
$one = Array (
0 => Array ('intTrackId' => 41, 'intAverageRating' => 10, 'bolNewRelease' => 0, 'dtDateAdded' => '2013-03-08 17:32:26' ),
1 => Array ('intTrackId' => 1, 'intAverageRating' => 7, 'bolNewRelease' => 0, 'dtDateAdded' => '2013-03-08 18:54:35' )
);
$two = Array (
0 => Array ('intTrackId' => 41, 'intAverageRating' => 5.5000, 'bolNewRelease' => 1, 'dtDateAdded' => '2014-03-25T09:39:28Q' ),
1 => Array ('intTrackId' => 361, 'intAverageRating' => 8.0000, 'bolNewRelease' => 1, 'dtDateAdded' => '2014-03-25T09:39:28Q' )
);
$result = array_udiff($two, $one, function($x, $y)
{
return $x['intTrackId']-$y['intTrackId'];
});
Yes it can be done with array_filter:
$array1 = array(...);
$array2 = array(...);
$newArray = array_filter($array2, function($item) use ($array1){
foreach($array1 as $elem){
if($item['intTrackId'] == $elem['intTrackId']){
return false;
}
}
return true;
});
I would first create a loop and store all track IDs from the first array in a separate array.
Then I'd loop over the second array and delete those keys that exist in the track ID array.
$track_ids = array();
foreach($array1 as $index => $items) {
$track_ids[$items['intTrackId']] = $index;
}
foreach($array2 as $items) {
if (isset($track_ids[$items['intTrackId']])) {
unset($array2[$track_ids[$items['intTrackId']]]);
}
}

array transformation in 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);

Categories