Combine array in php [duplicate] - php

This question already has answers here:
Add 2 values to 1 key in a PHP array
(7 answers)
Closed last month.
I have array
array
0 =>
array
2 => int 50000
1 =>
array
2 => int 30000
2 =>
array
1 => int 25000
3 =>
array
1 => int 20000
4 =>
array
1 => int 10000
I need to create array the result is:
array
2 => int 50000
2 => int 30000
1 => int 25000
1 => int 20000
1 => int 10000
Thank for all.
sorry, my english very bad :(

PHP doesn't allow arrays to have the same keys. This will show how php will handle a foreach loop wich is rewriting the array into a new one with desired key and value
$array = array(
0 =>
array(
2 => 50000),
1 =>
array(
2 => 30000),
2 =>
array(
1 => 25000),
3 =>
array(
1 => 20000),
4 =>
array(
1 => 10000)
);
$new_array = array();
foreach($array as $data)
{
foreach($data as $key => $val)
{
$new_array[$key] = $val;
}
}
var_dump($new_array);
This will output
array(2) {
[2]=>
int(30000)
[1]=>
int(10000)
}
Live Sample
As you can see keys are overwritten on each loop becuase they are identical and so are values, i think you can use the above function to have a one level array removing keys from $new_array
foreach($data as $key => $val)
{
$new_array[] = $val;
}
Live Sample

This does what you want (without preserving children keys, since you cannot have multiple elements with the same key):
$flat_array = array_map('current', $array);
Try here: http://codepad.org/1h7mKbqe

Related

How to create a new array using of another array keys?

Is it possible to create a new array from the keys of another like following?
it is a dynamic array chk_values are dynamically changed depends on condition
Array
(
[actBtn] => update
[chkCount] => 5
[chk_1] => 2
[chk_2] => 3
[chk_3] => 2
[chk_4] => 3
[chk_5] => 3
)
and i want array like this for update database
$chckpoint = Array(
[chk_1] => 2
[chk_2] => 3
[chk_3] => 2
[chk_4] => 3
[chk_5] => 3)
Simply process the original array and only move to the new array where the key starts with chk_
$in = ['actBtn' => 'update',
'chkCount' => 5,
'chk_1' => 2,
'chk_2' => 3,
'chk_3' => 2,
'chk_4' => 3,
'chk_5' => 3
];
foreach($in as $k=>$v){
if ( strpos($k,'chk_') !== false ){ $chckpoint[$k] = $v; }
}
print_r($chckpoint);
RESULT
Array
(
[chk_1] => 2
[chk_2] => 3
[chk_3] => 2
[chk_4] => 3
[chk_5] => 3
)
You can simply take the input array and check for all keys beginning with chk_. If the key matches, take it to the new array.
$chckpoint = [];
foreach($input as $key => $value)
{
if(substr($key, 0, 4) == 'chk_') $chkpoint[$key] = $value;
}

sorting chapters in an 4 level array

I want to sort an existing array into 4 dimension array:
the "list" array that I have:
1 => "text1"
10 => "text10"
11 => "text11"
101 => "text101"
1011 => "text1011"
10123 => "text10123"
2 => "text2"
20 => "text20"
201 => "text201"
2011 => "text2011"
20111 => "text20111"
the array I want is one that has all the data sorted by each number (in 4 dimention) i mean that i won't have an other array in the end of $chapter[1] containing 10123 => "text10123" (this one will be in the same array as this one : 1011 => "text1011"
here is an exemple of the array i want
$chapter[1] = array(
1 => "text1", array(
10 => "text10", 11 => "text11", array(
101 => "text101", array(
1011 => "text1011", 10123 => "text10123" )
)
)
);
I guess you can use for-loop and break each number to digits (with str-split) and then add the arrays.
Consider the following example:
$arr = array(1, 11, 111, 113, 2, 21, 211, 213);
$chapter = array(); // this will be your result array
foreach($arr as $e) {
$digits = str_split($e);
$current = &$chapter;
foreach($digits as $d) {
if (!isset($current[$d]))
$current[$d] = array();
$current = &$current[$d];
}
}
Notice I used & to assign the new array to the original result one.
I know your array has missing key and not have to be sorted but I guess you can overcome it (filter and sort the array before)
Edited
After question has change this is the example code: (when key DATA is for the text you want and key CHILDREN for the next elements)
$arr = array(1 => "text1", 10 => "text10", 11 => "text11", 101 => "text101", 1011 => "text1011", 10123 => "text10123", 2 => "text2", 20 => "text20", 201 => "text201", 2011 => "text2011", 20111 => "text20111");
$chapter = array();
foreach($arr as $key => $val) {
$digits = str_split(substr($key, 0, 4)); // if 4 digits is the max depth
$current = &$chapter;
foreach($digits as $d) {
if (!isset($current["CHILDREN"][$d]))
$current["CHILDREN"][$d] = array();
$current = &$current["CHILDREN"][$d];
}
$current["DATA"] = $val;
}

PHP performing logical AND of two arrays

I have two arrays with exactly the same key names but different binary values. I would like to form an array containing the logical AND of the binary values in each array.
eg:
$array1 = Array ([Ant] => 1 [Arm] => 1 [Ash] => 1 [AUB] => 0 [Bas] => 1 [Bay] );
$array2 = Array ([Ant] => 1 [Arm] => 0 [Ash] => 1 [AUB] => 1 [Bas] => 1 [Bay] );
$finalArray = ($array1 AND $array2);
//The expected output is:
$finalArray = Array ([Ant] => 1 [Arm] => 0 [Ash] => 1 [AUB] => 0 [Bas] => 1 [Bay] );
You can use the array_walk function
array_walk($array1, function(&$value, $key) use ($array2) {
$value = $array2[$key] && $value;
});
The $array1 will have the final value

PHP - Unexpected array_merge_recursive() output

I have this code
$a1 = array(
'success' => TRUE,
'data' => array(
'foo' =>
array(
21 =>
array(
1 =>
array(1, 2, 3, 4, 5)
)
)
)
);
$a2 = array(
'success' => TRUE,
'data' => array(
'foo' =>
array(
21 =>
array(
7 =>
array(6, 7, 8, 9, 10)
)
)
)
);
$results = array();
$results = array_merge_recursive($results, $a1['data']);
$results = array_merge_recursive($results, $a2['data']);
var_dump($results);
From what I understood of array_merge_recursive(), I am expecting the results would be
array
'foo' =>
array
21 =>
array
1 =>
array
0 => int 1
1 => int 2
2 => int 3
3 => int 4
4 => int 5
7 =>
0 => int 6
1 => int 7
2 => int 8
3 => int 9
4 => int 10
Instead I get this
array
'foo' =>
array
21 =>
array
1 =>
array
0 => int 1
1 => int 2
2 => int 3
3 => int 4
4 => int 5
22 =>
array
7 =>
array
0 => int 6
1 => int 7
2 => int 8
3 => int 9
4 => int 10
Where did the 22 index come from? Why is it outputting differently? Did I use the function wrong?
array_merge_recursive merges elements/arrays from the same depth as the first array, but if both arrays the key is a numerical index and they are the same it then appends to it. This is what is happening in your situation. since then your array is appended at 2nd level where index 21 is found by creating index 22. To receive the desired output you have change your index 21 to a string key like "x21"
Notes from php manual
If the input arrays have the same string keys, then the values for
these keys are merged together into an array, and this is done
recursively, so that if one of the values is an array itself, the
function will merge it with a corresponding entry in another array
too. If, however, the arrays have the same numeric key, the later
value will not overwrite the original value, but will be appended.
I just came across the same issue, I wanted to merge the arrays but surprisingly found the keys were changed automatically in the result. The reason was because my "keys" are string of decimal numbers, without any alphabetic characters.
But luckily I noticed that if the keys have alphabetic characters, they could be reserved. So just came up with the following idea, which would append a letter 'S' to each key recursively before the merge, and later remove it in the final result.
Please refer to the enhanced_array_merge_recursive function for details:
<?php
$aa = [
'10' => 'book',
'14' => ['cat'],
];
$ab = [
'12' => 'cd',
'18' => 'cup',
'14' => ['dog'],
];
var_dump(enhanced_array_merge_recursive($aa, $ab));
function revise_keys($source)
{
if (!is_array($source)) {
return $source;
}
$target = [];
foreach ($source as $key => $value) {
$target['S' . $key] = revise_keys($value);
}
return $target;
}
function revert_keys($source)
{
if (!is_array($source)) {
return $source;
}
$target = [];
foreach ($source as $key => $value) {
$target[substr($key, 1 - strlen($key))] = revert_keys($value);
}
return $target;
}
function enhanced_array_merge_recursive(...$candidates)
{
$merged = [];
foreach ($candidates as $candidate) {
if (!is_array($candidate)) {
continue;
}
$merged = array_merge_recursive($merged, revise_keys($candidate));
}
return revert_keys($merged);
}
Output looks like following:
array(4) {
[10] =>
string(4) "book"
[14] =>
array(1) {
[0] =>
array(2) {
[0] =>
string(3) "cat"
[1] =>
string(3) "dog"
}
}
[12] =>
string(2) "cd"
[18] =>
string(3) "cup"
}

Why multisort works only in the first depth of array?

I thought that the function array_multisort can sort multidimensional array, but this code does not work.
Code:
$values = array(0, 2, 1, array(0, 2, 1));
array_multisort($values, SORT_ASC);
var_dump($values);
Return:
array(4) [
0 => 0
1 => 1
2 => 2
3 => array(3) [
0 => 0
1 => 2 //should be 1
2 => 1 //should be 2
]
]
Why the array in array is not sorted? Thanks
You can try
sort_recursive($values);
var_dump($values);
Output
array (size=4)
0 => int 0
1 => int 1
2 => int 2
3 =>
array (size=3)
0 => int 0
1 => int 1
2 => int 2
Function Used
function sort_recursive(&$array) {
sort($array);
foreach ( $array as &$v ) {
is_array($v) and sort_recursive($v);
}
}
is because the array() is in a multidimentional form
try this link to see how to sort multidimensional array click here

Categories