I want to merge two trees, in a multidimensional to one tree in the md array in php:
$array[1] = Array
[0] => a
[1] => b
[2] => c
$array[2] = Array
[0] => d
[1] => e
[2] => f
result:
$array[1] = Array
[0] => ad
[1] => be
[2] => cf
You could try this:
<?php
foreach($array[1] as $key => $value)
{
$array[1][$key] = $value.$array[2][$key];
}
?>
We can use array function to solve this Problem Like this :
$array = array('a','b','c');
$array2 = array('d','e','f');
$c = array_combine($array, $array2);
foreach($c as $key=>$value){
$data[] = $key.$value;
}
print_r($data);
Related
I need to merge 2 arrays and i have found lot of examples here on stackoverflow, but nothing has worked for me, in my case, so i explain my case:
Arrays (can be one, two, or three, or more...):
Array ( [0] => name-file_icon_001_00.png-
[1] => name-file_icon_002_00.png-
[2] => name-file_icon_003_00.png- )
Array ( [0] => rel
[1] => rel
[2] => rel )
Or can be two:
Array ( [0] => name-file_icon_001_00.png-
[1] => name-file_icon_002_00.png- )
Array ( [0] => rel
[1] => rel )
Or one:
Array ( [0] => name-file_icon_001_00.png- )
Array ( [0] => rel )
Need to insert the relative value "[0] => rel" with "[0] => name-file_icon_001_00.png-"
Expected result (merged):
Array ( [0] => name-file_icon_001_00.png-rel
[1] => name-file_icon_002_00.png-rel
[2] => name-file_icon_003_00.png-rel )
Reading around the web, seems that not exist a native function for make this.
Please, hope in your help :)
A simple foreach loop using the index and value parameters will do it in no time
Example
$a1 = ['name-file_icon_001_00.png-',
'name-file_icon_002_00.png-',
'name-file_icon_003_00.png-'
];
$a2 = ['rel1','rel2','rel3'];
foreach ($a1 as $i => $v){
$new[] = $v . $a2[$i];
}
print_r($new);
RESULT
Array
(
[0] => name-file_icon_001_00.png-rel1
[1] => name-file_icon_002_00.png-rel2
[2] => name-file_icon_003_00.png-rel3
)
You can map each array to a function that concatenates them:
$result = array_map(function($a, $b) { return $a.$b; }, $one, $two);
If you define one array with subarrays then you can unpack that array ...:
$array = [$one, $two];
$result = array_map(function($a, $b) { return $a.$b; }, ...$array);
Or for fun, you can extract each column from the subarrays and implode them:
$array = [$one, $two];
for($i=0; $a=array_column($array, $i); $i++) {
$result[] = implode($a);
}
What would be the most efficient PHP way to get unique values from an array of arrays and sort them by number of occurrences from most frequent to least?
Example input array:
Array
(
[0] => Array
(
[0] => A
[1] => B
[2] => C
[3] => D
)
[1] => Array
(
[0] => A
[1] => C
[2] => D
)
[2] => Array
(
[0] => C
[1] => F
[2] => X
)
)
Would result in this output array:
Array
(
[0] => C // 3
[1] => A // 2
[2] => D // 2
[3] => B // 1
[4] => F // 1
[5] => X // 1
)
The alphabetical order of values with same number of occurrences is not important.
So far I'm merging the array of arrays:
$all_posts = call_user_func_array( 'array_merge', $results );
Then creating a new array where values become keys. And values are the number of times they occur in the original array of arrays.
$posts_by_count = array();
foreach( $all_posts as $apost ) {
$posts_by_count[ $apost ] = 0;
foreach( $results as $tag_posts ) {
if( in_array( $apost, $tag_posts ) ) {
$posts_by_count[ $apost ]++;
}
}
}
Then I can sort by value
arsort($posts_by_count);
And create a new array where keys become values again.
$sorted_posts = array();
foreach($posts_by_count as $k => $v) {
$sorted_posts[] = $k;
}
pprint( $sorted_posts );
What would be a more efficient way to do that?
The simplest I can come up with is to start with the array_merge(), but using the splat (...) to merge all of the arrays. Then use the inbuilt array_count_values() to summarize the values and then arsort() to sort them...
$all_posts = array_merge(...$results );
$posts_by_count = array_count_values($all_posts);
arsort($posts_by_count);
This gives the output of...
Array
(
[C] => 3
[A] => 2
[D] => 2
[B] => 1
[F] => 1
[X] => 1
)
using
print_r(array_keys($posts_by_count));
gives...
Array
(
[0] => C
[1] => A
[2] => D
[3] => B
[4] => F
[5] => X
)
That's simple, first iterate to count occurences, finally use arsort() to sort it by value in descending order:
<?php
// sample data
$arr = [
['A', 'B', 'C', 'D'],
['A', 'C', 'D'],
['C', 'F', 'X']
];
// counting
$newArr = [];
foreach ($arr as $subarr) {
foreach ($subarr as $char) {
$newArr[$char] = (!array_key_exists($char, $newArr))
? 1
: $newArr[$char] = $newArr[$char] + 1;
}
}
// sort by value in DESC order
arsort($newArr);
// To get exactly what you want (without counting) just iterate $newArr and writ is as a $flatArr
$flatArr = [];
foreach ($newArr as $index => $item) {
$flatArr[] = $index;
}
// or with array_keys which _may_ be unstable #see: https://stackoverflow.com/q/10336363/1066240
$flatArrArrayKeys = array_keys($newArr);
// output
$newArrHr = print_r($newArr, 1);
$flatArrHr = print_r($flatArr, 1);
echo "<pre>OUTPUT:
With count:
$newArrHr
As flat array:
$flatArrHr
As flat array with array_keys()
$flatArrArrayKeys
";
$json_str1 = '[{"13:00":"1"},{"14:00":"1"},{"15:30":"1"},{"16:30":"1"},{"1:00":"1"}]';
$json_str2 = '[{"13:00":"1"},{"14:00":"1"},{"15:30":"1"},{"12:30":"1"}]';
These are two JSON strings and I want the result like difference between them like {"1:00":"1"} and one more {"12:30":"1"}
The solution of this has a many aspects, cause there's 3 different values:
{"16:30":"1"},{"1:00":"1"}
{"12:30":"1"}
Firstly, you can convert your JSON string into array with json_decode($str,true):
json_decode($json_str1, true);
json_decode($json_str2, true);
Outputs like:
Array
(
[0] => Array
(
[13:00] => 1
)
...
Then create combined array with values like JSON object elements with foreach loop:
$str1 = [];
foreach($data1 as $row){
$str1[] = json_encode($row);
}
Outputs like:
Array
(
[0] => {"13:00":"1"}
[1] => {"14:00":"1"}
[2] => {"15:30":"1"}
[3] => {"16:30":"1"}
[4] => {"1:00":"1"}
)
...
Then you can find the difference between this two arrays, but, you need to do it in both ways (compare $array1 with $array2 and $array2 with $array1):
$dif1 = array_diff($str1, $str2);
$dif2 = array_diff($str2, $str1);
Outputs:
Array
(
[3] => {"16:30":"1"}
[4] => {"1:00":"1"}
)
Array
(
[3] => {"12:30":"1"}
)
Finally you can merge the result with:
$fin = array_merge($dif1, $dif2);
Outputs:
Array
(
[0] => {"16:30":"1"}
[1] => {"1:00":"1"}
[2] => {"12:30":"1"}
)
All of this you can put in a separate function like:
function getDifference2JSONstrings($jsonStr1, $jsonStr2){
$data1 = json_decode($jsonStr1, true);
$data2 = json_decode($jsonStr2, true);
$str1 = [];
$str2 = [];
foreach($data1 as $row){
$str1[] = json_encode($row);
}
foreach($data2 as $row){
$str2[] = json_encode($row);
}
return array_merge(array_diff($str1, $str2), array_diff($str2, $str1));
}
$res = getDifference2JSONstrings($json_str1, $json_str2);
print_r($res);
Outputs an array:
Array
(
[0] => {"16:30":"1"}
[1] => {"1:00":"1"}
[2] => {"12:30":"1"}
)
Demo
I have an array as:
Array
(
[0] => Array
(
[0] => A
[1] => B
)
[1] => C
[2] => Array
(
[0] => D
[0] => E
)
)
and I want to convert it like:
Array
(
[0] => Array
[0] => A
[1] => B
[2] => C
[3] => D
[4] => E
)
i.e I want all the values in the first array (irrespective of their indexes) to be aligned in the second array.
You need to write a custom script which merge arrays by your logic.
Example:
<?php
$a = [
['A', 'B'],
'C',
['D', 'E']
];
$result = [];
foreach ($a as $v) {
if (is_array($v))
$result = array_merge($result, $v);
else
$result[] = $v;
}
print_r([$result]);
You can user this :
$array = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)),0);
I have copied from here how Turning multidimensional array into one-dimensional array
Please try with below code:
$arr = array(
0 => array("A", "B"),
1 => "C",
2 => array("D", "E"),
);
$result = array();
$response = arrayIndex($arr, $result);
function arrayIndex($arr, $result){
foreach ($arr as $key => $value) {
if(is_array($value)){
$result = $this->arrayIndex($value, $result);
} else {
array_push($result, $value);
}
}
return $result;
}
NOTE: This function will convert n level of array elements into a single level array.
I'm having trouble converting a string to a multi-dimensional array in php. This is my string:
$String = a,b,c|d,e,f|g,h,y|
This is what I'm trying:
$one=explode("|",$String);
foreach ($one as $item)
{
$one=explode(",",$one);
}
I'd like to create this array:
$array={ {a,b,c}, {d,e,f}, {g,h,y} };
Try with -
$one=explode("|",$String);
$array = array();
foreach ($one as $item){
$array[] = explode(",",$item);
}
Try this code:
$string = 'a,b,c|d,e,f|g,h,y|';
$arr = array_map(function($iter){ return explode(',',$iter);},explode('|',$string));
Hope it help a bit.
You have almost done it right, except for the cycle part. Try this
$result = [];
$String = 'a,b,c|d,e,f|g,h,y|';
$firstDimension = explode('|', $String); // Divide by | symbol
foreach($firstDimension as $temp) {
// Take each result of division and explode it by , symbol and save to result
$result[] = explode(',', $temp);
}
print_r($result);
Try this-
$String = 'a,b,c|d,e,f|g,h,y|';
$one = array_filter(explode("|", $String));
print_r($one); //Array ( [0] => a,b,c [1] => d,e,f [2] => g,h,y )
$result = array_map('v', $one);
function v($one) {
return explode(',',$one);
}
print_r($result); // Array ( [0] => Array ( [0] => a [1] => b [2] => c ) [1] => Array ( [0] => d [1] => e [2] => f ) [2] => Array ( [0] => g [1] => h [2] => y ) )
Use this code
$String= 'a,b,c|d,e,f|g,h,y|';
$one=explode("|",$String);
print_r(array_filter($one));
Output will be
Array
(
[0] => a,b,c
[1] => d,e,f
[2] => g,h,y
)