Create an array based on multiple arrays by key - php

Please help me to combine four arrays in one.
I have to compare main array keys and if the key of the secondaries arrays coincides, add them to the new array.
I tried to combine different php functions, but without the expected result and nothing relevant.
This is the main array.
[0] => Array
(
[1] => "Category1"
[2] => "Category2"
[3] => "Category3"
[4] => "Category4"
)
These are the secondaries arrays
[1] => Array
(
[1] "user_test_[1]" key 1 map to --> [1] Category1
[2] "user_test_[2]" key 2 map to --> [2] Category2
[3] "user_test_[3]" key 3 map to --> [3] Category3
[4] "user_test_[4]" key 4 map to --> [4] Category4
)
[2] => Array
(
2: "user_prod_[2]" key 2 map to --> [2] Category2
4: "user_prod_[4]" key 4 map to --> [4] Category4
)
[3] => Array
(
[3] "user_uat_[3]" key 3 map to --> [3] Category3
[4] "user_uat_[4]" key 4 map to --> [4] Category4
)
New array results in php format:
$array_result = array(
'Category1'=>array(
'user_test_[1]'
),
'Category2'=>array(
'user_test_[2]',
'user_prod_[2]'
),
'Category3'=>array(
'user_test_[3]',
'user_uat_[3]'
),
'Category4'=>array(
'user_test_[4]',
'user_prod_[4]',
'user_uat_[4]'
)
);
Main array in in php format:
$array_cat = array(1=>"Category1", 2=>"Category2", 3=>"Category3", 4=>"Category4");
These are the secondaries arrays in php fromat:
$array_usrtest = array(1=>"user_test_[1]", 2=>"user_test_[2]", 3=>"user_test_[3]", 4=>"user_test_[4]");
$array_usruat = array(3=>"user_uat_[3]", 4=>"user_uat_[4]");
$array_usrprod = array(2=>"user_prod_[2]", 4=>"user_prod_[4]");
Expected results
array{
["Category1"]=>array(1)
{
[0]=>"user_test_[1]"
}
["Category2"]=>array(2)
{
[0]=>"user_test_[2]"
[1]=>"user_prod_[2]"
}
["Category3"]=>array(3)
{
[0]=>"user_test_[3]"
[2]=>"user_uat_[3]"
}
["Category4"]=>array(3)
{
[0]=>"user_test_[4]"
[1]=>"user_prod_[4]"
[2]=>"user_uat_[4]"
}
}

Here is simple solution, which it's not very good, because it is solution for your specific values, but it is good start point and if you want, you can improve it:
<?php
$array_cat = array(1=>"Category1", 2=>"Category2", 3=>"Category3", 4=>"Category4");
$array_usrtest = array(1=>"user_test_[1]", 2=>"user_test_[2]", 3=>"user_test_[3]", 4=>"user_test_[4]");
$array_usruat = array(3=>"user_uat_[3]", 4=>"user_uat_[4]");
$array_usrprod = array(2=>"user_prod_[2]", 4=>"user_prod_[4]");
$result = [];
foreach ($array_cat as $k => $v) {
$result[$v] = []; // fill result array with categories
}
$values = array_merge($array_usrtest, $array_usruat, $array_usrprod); // merge arrays into one (all items)
foreach ($values as $k => $value) { // iterate over all values
preg_match('!\d+!', $value, $match); // get index in [index]
$result['Category' . $match[0]][] = $value; // append values to category
}
echo '<pre>';
var_dump($result);
Result:
array(4) {
["Category1"]=>
array(1) {
[0]=>
string(13) "user_test_[1]"
}
["Category2"]=>
array(2) {
[0]=>
string(13) "user_test_[2]"
[1]=>
string(13) "user_prod_[2]"
}
["Category3"]=>
array(2) {
[0]=>
string(13) "user_test_[3]"
[1]=>
string(12) "user_uat_[3]"
}
["Category4"]=>
array(3) {
[0]=>
string(13) "user_test_[4]"
[1]=>
string(12) "user_uat_[4]"
[2]=>
string(13) "user_prod_[4]"
}
}

I would say merge all array and then build the category array
$arrs = array_merge($array_usrtest, $array_usruat, $array_usrprod);
$categories = array_fill_keys($array_cat, []);
array_walk($arrs, function($item) use (& $categories){
preg_match('#(.*)\[(\d)\]#', $item, $matches);
$key = $matches[2];
$categories['Category' . $key][] = $item;
});
print_r($categories);

Based on yours answers:
<?php
$array_cat = array(1=>"Category1", 2=>"Category2", 3=>"Category3", 4=>"Category4");
$array_usrtest = array(1=>"user_test_[1]", 2=>"user_test_[2]", 3=>"user_test_[3]", 4=>"user_test_[4]");
$array_usruat = array(3=>"user_uat_[3]", 4=>"user_uat_[4]");
$array_usrprod = array(2=>"user_prod_[2]", 4=>"user_prod_[4]");
$values = array_merge($array_usrtest, $array_usruat, $array_usrprod);
$result = [];
foreach ($array_cat as $key => $cat) {
foreach ($values as $k => $value) { // iterate over all values
preg_match('!\d+!', $value, $match); // get index in [index]
if ($key == $match[0]) {
$result[$cat][] = $value; //append values to category
}
}
}
echo '<pre>';
var_dump($result);
?>
Result:
array(4) {
["Category1"]=>
array(1) {
[0]=>
string(13) "user_test_[1]"
}
["Category2"]=>
array(2) {
[0]=>
string(13) "user_test_[2]"
[1]=>
string(13) "user_prod_[2]"
}
["Category3"]=>
array(2) {
[0]=>
string(13) "user_test_[3]"
[1]=>
string(12) "user_uat_[3]"
}
["Category4"]=>
array(3) {
[0]=>
string(13) "user_test_[4]"
[1]=>
string(12) "user_uat_[4]"
[2]=>
string(13) "user_prod_[4]"
}
}

Related

Create new Array under same key from multiple Array in PHP [duplicate]

This question already has answers here:
Transpose 2d array, join second level with commas, and join first level with pipes
(5 answers)
Closed 7 months ago.
I have the following array.
$a = array("Algebra", "Arithmetic");
$b = array("08/01/2020", "08/02/2019");
$c = array("08/01/2020", "08/02/2019");
print_r($a);
print_r($b);
print_r($b);
and the output is
Array(
[0] => Algebra
[1] => Arithmetic
)
Array(
[0] => 08/01/2020
[1] => 08/01/2019
)
Array(
[0] => 08/02/2020
[1] => 08/02/2019
)
And I want Array in the following structure.
Array(
[0] => Algebra,08/01/2020,08/02/2020
[1] => Arithmetic,08/01/2019,08/02/2019
)
I have tried $results = array_merge_recursive($a, $b, $c); but its not giving desire output.
Thanks for help in advance.
A simple foreach loop will suffice
$a = array("Algebra", "Arithmetic");
$b = array("08/01/2020", "08/02/2019");
$c = array("08/01/2020", "08/02/2019");
foreach( $a as $i=>$v ) {
$new[] = sprintf( '%s,%s,%s', $v, $b[$i], $c[$i] );
}
Firstly, when you find yourself using sequentially-named variables it almost always means that they should actually be an array:
$a = array("Algebra", "Arithmetic");
$b = array("08/01/2020", "08/02/2019");
$c = array("08/01/2020", "08/02/2019");
$better_array = [$a, $b, $c];
var_dump($better_array);
Output:
array(3) {
[0]=>
array(2) {
[0]=>
string(7) "Algebra"
[1]=>
string(10) "Arithmetic"
}
[1]=>
array(2) {
[0]=>
string(10) "08/01/2020"
[1]=>
string(10) "08/02/2019"
}
[2]=>
array(2) {
[0]=>
string(10) "08/01/2020"
[1]=>
string(10) "08/02/2019"
}
}
Once they're in an proper array you can use array_column()
$out = [];
for($i=0, $c=count($better_array[0]); $i < $c; ++$i) {
$out[] = array_column($better_array, $i);
}
var_dump($out);
Output:
array(2) {
[0]=>
array(3) {
[0]=>
string(7) "Algebra"
[1]=>
string(10) "08/01/2020"
[2]=>
string(10) "08/01/2020"
}
[1]=>
array(3) {
[0]=>
string(10) "Arithmetic"
[1]=>
string(10) "08/02/2019"
[2]=>
string(10) "08/02/2019"
}
}
And if that comma-delimited string is what you actually want, then use implode():
$out = [];
for($i=0, $c=count($better_array[0]); $i < $c; ++$i) {
$out[] = implode(',', array_column($better_array, $i));
}
var_dump($out);
Output:
array(2) {
[0]=>
string(29) "Algebra,08/01/2020,08/01/2020"
[1]=>
string(32) "Arithmetic,08/02/2019,08/02/2019"
}
Lastly, you should avoid print_r() as it tends to produce misleading output. Eg: https://3v4l.org/ThSLb
You don't get anything built-in for this purpose. You need to build a custom function for this. You can try this-
<?php
$a = array("Algebra", "Arithmetic");
$b = array("08/01/2020", "08/01/2019");
$c = array("08/02/2020", "08/02/2019");
function mergeAssoc()
{
// You can get variable number of arguments|array by this.
$args = func_get_args();
$master = array();
foreach ($args as $arg)
{
foreach ($arg as $i => $v)
{
$master[$i][] = $v;
}
}
return $master;
}
$res = mergeAssoc($a, $b, $c);
print_r($res);
Note: It will return a multidimensional array. Not an array of comma-separated values.
Output:
Array
(
[0] => Array
(
[0] => Algebra
[1] => 08/01/2020
[2] => 08/02/2020
)
[1] => Array
(
[0] => Arithmetic
[1] => 08/01/2019
[2] => 08/02/2019
)
)
and if we use foreach then our desire output will be there with array separated by comma.
foreach ($res as $key => $value) {
$result[] = implode(',', $value);
}
and output of print_r($result); is
Array
(
[0] => Algebra,08/01/2020,08/02/2020
[1] => Arithmetic,08/01/2019,08/02/2019
)

Combine multiple arrays with identica keys and different values

I have this two arrays that are generated in two foreach loops and I want to set the first array as keys and the second one as values.
after I use this code
foreach ($difference AS $j) {
$fv = $cate->getFilterValueByFeatureID($j);
foreach ($fv AS $z) {
$array = array(
$j => $z
);
var_dump($array);
}
}
this is what I get
array(1) {
[6]=>
int(15)
}
array(1) {
[6]=>
int(20)
}
array(1) {
[8]=>
int(26)
}
array(1) {
[8]=>
int(27)
}
array(1) {
[8]=>
int(33)
}
and I want this result
array(1){
[6] => array(
[0] => 15
[1] => 20
)
array(1){
[8] => array(
[0] => 26
[1] => 27
[2] => 33
)
Like this (untested)
$result = [];
foreach ($difference AS $j) {
$fv = $cate->getFilterValueByFeatureID($j);
foreach ($fv AS $z) {
if(!isset($result[$j])) $result[$j] = [];
$result[$j][] = $z;
}
}
var_dump($result);

Compare two array and diplay the value 2nd array value which is not present in the 1st array

$data1 -
Array([0] => Array([file_id_fk] => 1)
[1] => Array([file_id_fk] => 2)
[2] => Array([file_id_fk] => 5)
[3] => Array([file_id_fk] => 3)
........
[300]=>Array([file_id_fk] => 3)
$data2 -
Array([0] => Array
([file_id] => 1
[file_sender_type] => 1
[file_sender_id] => 1
[file_subject] => test 1)
......
[360]=>Array...
Here i want to compare $data1->file_id_fk with $data2->file_id and print the $data2 values that are not present in $data1.
It looks like you'll want to use array_diff(), but being that you want the extra values from $data2, you'll want to change the order around:
array_diff($data2, $data).
Read the full documentation here: http://php.net/manual/en/function.array-diff.php
Imagine yourself being the PHP Parser. How would you like to see the code you had to parse? I asked myself this question and came up with the following:
$valuesThatAreInTheFirstArrayButNotInTheSecond = array_diff($theFirstArray, $theSecondArray);
I can't make it much more.
As PHP Parser, I am well documented. There's a website on the so called internet that describes how I do and like to do things. You can find the documentation on how I want to parse array_diff() in the PHP.net Manual
Edit
Because you have an array in an array (inception?), you can use the current() function around the array. This will grab the array's current key. As there is only one key in your array, it will always pick that one.
So that will make:
$valuesThatAreInTheFirstArrayButNotInTheSecond = array_diff(current($theFirstArray), current($theSecondArray));
Showing the difference can be done like this:
if (array_key_exists('file_id', $valuesThatAreInTheFirstArrayButNotInTheSecond)) {
echo $valuesThatAreInTheFirstArrayButNotInTheSecond['file_id'];
}
This will not work on older PHP versions (I am working with 5.4 currently).
$data1ID = array_column($data1, 'file_id_fk');
$results = array_filter($data2, function($v) use ($data1ID){
return !in_array($v['file_id'], $data1ID);
});
print_r($data1);
print_r($data2);
print_r($results);
This is my input data and results:
/vhost/virtual/sandbox/public/index.php:55
array(5) {
[0] = array(1) {
[file_id_fk] = int(1) 1
}
[1] = array(1) {
[file_id_fk] = int(1) 2
}
[2] = array(1) {
[file_id_fk] = int(1) 5
}
[3] = array(1) {
[file_id_fk] = int(1) 3
}
[4] = array(1) {
[file_id_fk] = int(1) 3
}
}
/vhost/virtual/sandbox/public/index.php:56
array(3) {
[0] = array(4) {
[file_id] = int(1) 1
[file_sender_type] = int(1) 1
[file_sender_id] = int(1) 1
[file_subject] = string(6) "test 1"
}
[1] = array(4) {
[file_id] = int(1) 5
[file_sender_type] = int(1) 5
[file_sender_id] = int(1) 5
[file_subject] = string(6) "test 5"
}
[2] = array(4) {
[file_id] = int(1) 7
[file_sender_type] = int(1) 7
[file_sender_id] = int(1) 7
[file_subject] = string(6) "test 7"
}
}
/vhost/virtual/sandbox/public/index.php:57
array(1) {
[2] = array(4) {
[file_id] = int(1) 7
[file_sender_type] = int(1) 7
[file_sender_id] = int(1) 7
[file_subject] = string(6) "test 7"
}
}
finally got answer friends thank you so much
foreach($data1 as $val)
{
$data1[]=$val['file_id_fk'];
}
for($i=0 ; $i<=count($data2) ; $i++)
{
if(!in_array($data2[$i]['file_id'],$data1))
{
$data[] = $data2[$i];
}
}

How to Re-structure multi-dimensional array in PHP?

I have an array that looks like this:
array(3) {
[0]=>
array(2) {
[0]=>
string(10) "2012-11-14"
[1]=>
string(5) "3238"
}
[1]=>
array(2) {
[0]=>
string(10) "2012-11-13"
[1]=>
string(5) "3231"
}
[2]=>
array(2) {
[0]=>
string(10) "2012-11-13"
[1]=>
string(5) "3231"
}
I would like to write a foreach loop that would turn this array into:
array(2) {
[0]=>
array(1) {
"2012-11-14" => "3238"
}
[1]=>
array(1) {
"2012-11-13" => "3231"
}
So, basically, I would like to use the array element formatted as Y-M-D date as key to the second element in the array.
Given the following array...
$array = array(
0 => array(0 => "2012-11-14", 1 => "3238"),
1 => array(0 => "2012-11-13", 1 => "3231"),
2 => array(0 => "2012-11-13", 1 => "3231"),
);
putting it into a new array like this:
$new_array = array();
foreach ($array as $key => $item)
{
$new_array[$key][$item[0]] = $item[1];
}
print_r($new_array);
produces this output:
Array
(
[0] => Array
(
[2012-11-14] => 3238
)
[1] => Array
(
[2012-11-13] => 3231
)
[2] => Array
(
[2012-11-13] => 3231
)
)
My answer doesn't get rid of the duplicates, but the added dimension as specified in the original question means that duplicate dates as keys aren't an issue.
<?php
$data = array(
array("2012-11-14", "3238"),
array("2012-11-13", "3231"),
array("2012-11-13", "3231") // warning! when there are two record with same date, the second's count will be display
);
$result = array();
foreach ($data as $value) {
$result[$value[0]] = $value[1];
}
echo '<pre>';
print_r($result);
<?php
$newArray = array();
for($i=0;$i<count($arrayVariable);$i++)
{
$newArray[$arrayVariable[$i][0]] = $arrayVariable[$i][1];
}
echo '<pre>';print_r($newArray);echo '</pre>';
?>
Didn't test it but something like this should work in concept. Of course change arrayVariable to your variable.. but that aside.
You can use this code to get what you want:
$dates = array(
array("2012-11-01", "3238"),
array("2012-11-03", "4321")
);
print_r($dates);
$result = array();
foreach($dates as $value) {
$result[][$value[0]] = $value[1];
}
print_r($result);
The output will look like the requested form:
Array
(
[0] => Array
(
[2012-11-01] => 3238
)
[1] => Array
(
[2012-11-03] => 4321
)
)
Codepad demo: http://codepad.org/XAmUEdYh
However, I would personally prefer Aykut's solution. You would of course have a problem when you've got two records with the same date, but the overall array layout is a bit nicer ;).
Here is what I came up with:
<?php
$original = array(
array(
"2012-11-14",
"3238"
),
array(
"2012-11-13",
"3231"
),
array(
"2012-11-13",
"3231"
)
);
$newArray = array();
foreach($original as $subArray){
$newArray[] = array($subArray[0] => $subArray[1]);
}
var_dump($newArray);

Combine pairs to groups [PHP / Arrays]

I have pairs of items in an PHP array. Example:
<?php
$elements = array(
'tiger'=>'lion',
'car'=>'bike',
'lion'=>'zoo',
'truck'=>'plane'
);
?>
Now I want to combine these items so that all items which are connected in any way go to one group. Continuation of the example above:
<?php
$groups = array(
0=>array('tiger', 'lion', 'zoo'),
1=>array('car', 'bike'),
2=>array('truck', 'plane'
);
?>
Is this understandable? How could I achieve this?
I'm looking for a function which does this.
<?php
$elements = array(
'tiger' => 'lion',
'car' => 'bike',
'lion' => 'zoo',
'truck' => 'plane'
);
$groups = array();
foreach ($elements as $key => $val) {
$appended = false;
foreach ($groups as &$group) {
if ($group[0] == $key) {
array_unshift($group, $val);
$appended = true;
break;
}
}
if (!$appended) {
$groups[] = array($val, $key);
}
}
var_dump($groups);
Gives:
array(3) {
[0]=>
array(3) {
[0]=>
string(3) "zoo"
[1]=>
string(4) "lion"
[2]=>
string(5) "tiger"
}
[1]=>
&array(2) {
[0]=>
string(4) "bike"
[1]=>
string(3) "car"
}
[2]=>
array(2) {
[0]=>
string(5) "plane"
[1]=>
string(5) "truck"
}
}
Here's an O(n) solution:
$elements = array(
'tiger' => 'lion',
'car' => 'bike',
'lion' => 'zoo',
'truck' => 'plane'
);
$groups = array();
$sub = array();
$ignore = array();
foreach ( $elements as $key=>$value ) {
if ( isset($ignore[$key]) ) {
continue;
}
$sub = array($key, $value);
if ( isset($elements[$value]) ) {
$ignore[$value] = 1;
$sub[] = $elements[$value];
}
$groups[] = $sub;
}
print_r($groups);
Result:
Array
(
[0] => Array
(
[0] => tiger
[1] => lion
[2] => zoo
)
[1] => Array
(
[0] => car
[1] => bike
)
[2] => Array
(
[0] => truck
[1] => plane
)
)
The idea is simple:
Create a new array to hold your groups
Loop over the item array
Check if the group for the item exists in the group array - if it does not, create it
Put item in group

Categories