Custom array multidim values [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I had a problem with my code. for example, I have an array like this :
[
'a' => ['f', 'g'],
'b' => ['h', 'i'],
'c' => ['j', 'k']
]
I want to change my array to be like this:
[
['a' => 'f', 'b' => 'h', 'c' => 'j'],
['a' => 'g', 'b' => 'i', 'c' => 'k']
]
I need help to solve this. Thanks

I tested this on my local computer
<?php
$array = [
'a' => ['f', 'g'],
'b' => ['h', 'i'],
'c' => ['j', 'k']
];
$ultimate_array = array();
foreach($array as $key1 => $child_array)
{
foreach($child_array as $i => $key2)
{
if(empty($ultimate_array[$i])) $ultimate_array[$i] = array();
$ultimate_array[$i][$key1] = $key2;
}
}
print_r($ultimate_array);
?>

This is a simple demonstration:
<?php
$input = [
'a' => ['f', 'g'],
'b' => ['h', 'i'],
'c' => ['j', 'k']
];
$output = [];
foreach ($input as $key=>$entries) {
foreach ($entries as $entry) {
$output[$key][] = $entry;
}
}
var_dump($output);
Some would consider this variant more elegant:
<?php
$input = [
'a' => ['f', 'g'],
'b' => ['h', 'i'],
'c' => ['j', 'k']
];
$output = [];
array_walk($input, function($entries, $key) use (&$output) {
array_walk($entries, function($entry) use (&$output, $key) {
$output[$key][] = $entry;
});
});
var_dump($output);
The obvious output of both variants is:
array(3) {
["a"]=>
array(2) {
[0]=>
string(1) "f"
[1]=>
string(1) "g"
}
["b"]=>
array(2) {
[0]=>
string(1) "h"
[1]=>
string(1) "i"
}
["c"]=>
array(2) {
[0]=>
string(1) "j"
[1]=>
string(1) "k"
}
}

Related

Codeigniter - merge multiple associative array with condition

I need to merge multiple arrays into one where a specific key & its value are same. Here is the Sample_Array1
array(n) {
[0]=> array {
["a"]=> "m1"
["b"]=> "x2"
}
[1]=> array {
["a"]=> "n1"
["b"]=> "y2"
} ....
Sample_Array2 with one common key & other different ones.
array(n) {
[0]=> array {
["b"]=> "x2"
["c"]=> "p1"
}
[1]=> array {
["b"]=> "x2"
["d"]=> "q1"
}
[2]=> array {
["b"]=> "y2"
["e"]=> "r1"
} ....
Need to merge / append Sample_Array2 to Sample_Array1 where key-"b" & its value are same. The expected output:
array(n) {
[0]=>
array(2) {
["a"]=> "m1"
["b"]=> "x2"
["c"]=> "p1"
["d"]=> "q1"
}
[1]=>
array(2) {
["a"]=> "n1"
["b"]=> "y2"
["e"]=> "r1"
} ....
I have tried so many similar questions but couldn't find the exact result.
PHP merge arrays with a condition The answer given on this link is not solving the purpose, its making different array for each new key, while I need to append the new keys in one array.
This should work, assuming you have the "b" index in all sub arrays.
$array1 = array();
$array1[] = array("a" => "m1", "b" => "x2", "c" => null);
$array1[] = array("a" => "n1", "b" => "y2");
$array2 = array();
$array2[] = array("b" => "x2", "c" => "p1");
$array2[] = array("a" => null, "b" => "x2", "d" => "q1");
$array2[] = array("b" => "y2", "e" => "r1");
function merge_on_key($array1, $array2, $key) {
$result_array = array();
foreach($array1 as $key1 => $sub_array1) {
$merged_array = array();
$sub_array1 = array_filter($sub_array1);
foreach($array2 as $key2 => $sub_array2) {
$sub_array2 = array_filter($sub_array2);
if($sub_array1[$key] == $sub_array2[$key]) {
$merged_array = array_merge($sub_array1, $sub_array2, $merged_array);
unset($array2[$key2]);
}
}
if (!empty($merged_array)) {
$result_array[] = $merged_array;
}
}
return array_merge($result_array, $array2);
}
$final_array = merge_on_key($array1, $array2, "b");
print_r($final_array);
In case you have to match the "b" index within the $array1 itself too, then simply use it twice:
$array1 = merge_on_key($array1, $array1, "b");
$final_array = merge_on_key($array1, $array2, "b");
i really have no idea what you want to achieve here - but based on your description the following code works
$arrA = [
0 =>
[
'a' => 'm1',
'b' => 'x2'
],
1 =>
[
'a' => 'n1',
'b' => 'y2'
]
];
$arrB = [
0 =>
[
'b' => 'x2',
'c' => 'p1',
],
1 =>
[
'b' => 'x2',
'd' => 'q1',
],
2 =>
[
'b' => 'y2',
'e' => 'r1',
],
];
foreach($arrB AS $arrData)
{
foreach($arrData AS $key => $val)
{
if ((isset($arrData['a']) && $arrData['a'] == $arrA[0]['a']) || (isset($arrData['b']) && $arrData['b'] == $arrA[0]['b']))
{
$arrA[0][$key] = $val;
}
elseif ((isset($arrData['b']) && $arrData['b'] == $arrA[1]['a']) || (isset($arrData['b']) && $arrData['b'] == $arrA[1]['b']))
{
$arrA[1][$key] = $val;
}
}
}
print_r($arrA);
Created the arrays similar to yours. $new_array is the resultant array that you are looking for.
$a=array();
$a[0]=array('a'=>'m1', 'b'=>'x2');
$a[1]=array('a'=>'n1', 'b'=>'y2');
$b=array();
$b[0]=array('b'=>'x2', 'c'=>'p1');
$b[1]=array('b'=>'x2', 'd'=>'q1');
$b[2]=array('b'=>'y2', 'e'=>'r1');
foreach($a as $row){
//echo '<pre>'; print_r($row);
foreach($b as $c=>$row1){
//echo '<pre>'; print_r($row1);echo $c;die;
if($row['b']==$row1['b']){
$new_array[]=array_merge($row, $row1);
}
}
}echo '<pre>'; print_r($new_array);
// Gather all values of b from both arrays
$all_b = array_unique(array_merge(array_column($arr1, 'b'), array_column($arr2, 'b')));
$res = [];
// For each b value
foreach($all_b as $b) {
$temp = [];
// Scan the arrays for items with the same b value
foreach($arr1 as $a1) {
if ($a1['b'] == $b) $temp = array_merge($temp, $a1);
}
foreach($arr2 as $a2) {
if ($a2['b'] == $b) $temp = array_merge($temp, $a2);
}
// Save them to new array
$res[] = $temp;
}
print_r($res);
demo on eval

Store key & value in other array in php

How to take the keys and values ​​of a array after having positioned to a known key ?
My array :
[Bolivia] => a
[Brazil] => v
[Belgium] => d
[Cuba] => c
[Croatia] => x
[Finland] => j
[Germany] => m
[India] => n
[Japan] => w
Know key : [Croatia]
The search result :
[Finland] => j
[Germany] => m
[India] => n
[Japan] => w
I would solve it like this:
$known_key = 'Croatia';
$input = [....];
$result = [];
$passed = false;
foreach($input as $key => $value){
if($passed){
$result[$key] = $value;
}
if($key == $known_key){
$passed = true;
}
}
You can use array_slice to get it.
<?php
$array = array(
'Bolivia' => 'a',
'Brazil' => 'v',
'Belgium' => 'd',
'Cuba' => 'c',
'Croatia' => 'x',
'Finland' => 'j',
'Germany' => 'm',
'India' => 'n',
'Japan' => 'w');
$keys = array_keys($array);
$keys_flip = array_flip($keys);
var_dump(array_slice($array, $keys_flip['Croatia'] + 1));
output:
ei#localhost:~$ php test.php
array(4) {
["Finland"]=>
string(1) "j"
["Germany"]=>
string(1) "m"
["India"]=>
string(1) "n"
["Japan"]=>
string(1) "w"
}

Multidimensional associative unique

I have 2x multidimensional array's as show below:
$x = [
0=>[
'a',
'b'
],
1=>[
'c',
'd'
],
2=>[
'e',
'f'
]
];
$y = [
0=>[
'b',
'a'
],
1=>[
'g',
'h'
],
2=>[
'i',
'j'
]
];
I would like to merge the 2x array's (x and y) with an output like this
$xy = [
0=>[
'c',
'd'
],
1=>[
'e',
'f'
],
2=>[
'g',
'h'
],
3=>[
'i',
'j'
]
];
As you can see, $x[0] is equal to a,b and $y[0] equal to b,a and they are duplicated. I would like to know if it's possible for a,b as same as b,a , I don't know how to get my code to look like this. I want to eliminate my duplicated array (a,b != b,a). Any duplication are not allowed, is that possible?
This should give you exactly what you've requested. I've used multiple foreach() loops to test if the value is firstly part of the $Y array, if so then remove from both arrays using unset(). I've then merged the two arrays together, removed the empty array dimensions and reset the key count.
$x = [0=>['a','b'],1=>['c','d'],2=>['e','f']];
$y = [ 0=>['b','a'],1=>['g','h'],2=>['i','j']];
foreach ($x as $key=>$value) {
foreach($x[$key] as $k=>$v) {
$search = array_search($v, $y[$key], true); //Find if value is equal to value in Y using a search
if ($search !== false) { //If so then remove value
unset($y[$key][$search]); //Remove from Array Y
unset($x[$key][$search]); //Remove from Array X
}
}
}
$newArray = array_merge($x, $y); //Merge two arrays together
foreach($newArray as $key => $value) { //Remove empty dimensions from Array
if (count($newArray[$key]) <= 0) {
unset($newArray[$key]);
}
}
$newArray = array_values($newArray); //Re-Number Keys so there in order
var_dump($newArray); //Array Output
Output
{
[0] => array(2) {
[0] => string(1)
"c" [1] => string(1)
"d"
}[1] => array(2) {
[0] => string(1)
"e" [1] => string(1)
"f"
}[2] => array(2) {
[0] => string(1)
"g" [1] => string(1)
"h"
}[3] => array(2) {
[0] => string(1)
"i" [1] => string(1)
"j"
}
}
Edit
Added unset() to remove value from both arrays as it's mentions that you would NOT like to have duplicate data from either array shown in new array.

Convert multi-dimensional array key value

I have array like:-
$x = array(
'a' => array('aa' => array('aaa' => array(1, 2, 3))),
'b' => array('bb' => array('bbb' => array(1, 2, 3))),
);
Then, I want to modifying array to:-
$y = array(
1 => array('a', 'b'),
2 => array('aa', 'bb'),
3 => array('aaa', 'bbb'),
);
Please help me!
NB: if the last array 2,1,3 will be 2->a,b; 1->aa,bb; 3->aaa,bbb
You can try something like this:
$x = array(
'a' => array('aa' => array('aaa' => array(1, 2, 3))),
'b' => array('bb' => array('bbb' => array(1, 2, 3))),
);
$loop=true;
$item=array();
foreach ($x as $index => $value) {
if(!is_int($index)) $item[strlen($index)][]=$index;
while($loop){
foreach ($value as $sub_index => $sub_value) {
if (is_array($sub_value)) {
if(!is_int($sub_index)) $item[strlen($sub_index)][]=$sub_index;
$value=$sub_value;
}
else {
if(!is_int($sub_index))$item[strlen($sub_index)][]=$sub_index;
$loop=false;
}
}
}
$loop=true;
}
var_dump($item);
output
array(3) {
[1]=> array(2) { [0]=> string(1) "a" [1]=> string(1) "b" }
[2]=> array(2) { [0]=> string(2) "aa" [1]=> string(2) "bb" }
[3]=> array(2) { [0]=> string(3) "aaa" [1]=> string(3) "bbb" }
}
You could try the approach in the code below. And by the way, you could Quick-Test it Here.
<?php
$x = array(
'a' => array('aa' => array('aaa' => array(1, 2, 3))),
'b' => array('bb' => array('bbb' => array(1, 2, 3))),
);
$result = array();
$result[] = array_keys($x);
$tmp1 = [];
$tmp2 = [];
foreach($x as $k=>$arrData){
if(is_array($arrData)){
foreach($arrData as $k1=>$v1){
$tmp1[] = $k1;
if(is_array($v1)){
foreach($v1 as $k2=>$v2){
$tmp2[] = $k2;
}
}
}
}
}
$result[] = $tmp1;
$result[] = $tmp2;
var_dump($result);
//YIELDS:::
array (size=3)
0 =>
array (size=2)
0 => string 'a' (length=1)
1 => string 'b' (length=1)
1 =>
array (size=2)
0 => string 'aa' (length=2)
1 => string 'bb' (length=2)
2 =>
array (size=2)
0 => string 'aaa' (length=3)
1 => string 'bbb' (length=3)
Based on what you explained, I would suggest something like this:-
$x = array(
'a' => array('aa' => array('aaa' => array(1, 2, 3))),
'b' => array('bb' => array('bbb' => array(1, 2, 3))),
);
$y = array();
$l = array();
foreach ($x as $l[0] => $x2) {
foreach ($x2 as $l[1] => $x3) {
foreach ($x3 as $l[2] => $keys) {
for ($i = 0; $i < 3; $i++) {
if (isset($y[$keys[$i]])) {
$y[$keys[$i]][] = $l[$i];
} else {
$y[$keys[$i]] = array($l[$i]);
}
}
}
}
}
But please note that this code will fail if the depth changes or does not match the number of values that become keys...

Remove a set of fields from a array

Is there a native PHP function that can remove a set of keys from a array?
for eg. if I have a array like
array('a' => 'aaa', 'b' => 'bbb', 'c' => 'ccc', 'd' => 'ddd');
and I want to remove 'b', 'c' and get array('a' => 'aaa', 'd' => 'ddd'); ?
It's array_diff_key.
$input = array(...);
$remove = array_flip(array('a', 'b')); // 'a' and 'b' are the keys to remove
$output = array_diff_key($input, $remove);
See it in action.
$array = array('a', 'b', 'c', 'd')
foreach($array as $k=>$v){
if (in_array($v,array('b','c'))) unset($array[$k]);
}
An alternate to everyone else's answer, though all valid in their own way, is the array_splice function.
$foo = Array(
'a' => 'aaaa',
'b' => 'bbbb',
'c' => 'cccc',
'd' => 'dddd'
);
var_dump($foo);
array_splice($foo, 1, 2);
var_dump($foo);
Which produces:
array(4) {
["a"]=>
string(4) "aaaa"
["b"]=>
string(4) "bbbb"
["c"]=>
string(4) "cccc"
["d"]=>
string(4) "dddd"
}
array(2) {
["a"]=>
string(4) "aaaa"
["d"]=>
string(4) "dddd"
}
If you don't have too many fields to remove, you can use unset():
unset($foo['b']);
unset($foo['c']);
var_dump($foo)

Categories