How to combine multidimension array
<?php
$array[0] = [1=>[2=>[4=>[20=>""]]]];
$array[1] = [1=>[2=>[5=>[21=>""]]]];
$array[2] = [1=>[2=>[5=>[22=>""]]]];
$array[3] = [1=>[2=>[5=>[23=>""]]]];
$array[4] = [1=>[2=>[5=>[25=>""]]]];
$array[5] = [3=>[9=>[12=>[33=>""]]]];
$array[6] = [3=>[9=>[12=>[34=>""]]]];
$array[7] = [3=>[9=>[12=>[38=>""]]]];
?>
how to convert to be like:
$arrays = [1=>[2=>[4=>[20=>""],5=>[21=>"",22=>"",25=>""]]],[3=> [9 => [12 => [33 => "",38 => ""]]]]];
I am tried using array_merge :
$arrays = [];
foreach ($array as $val)
{
$arrays = array_merge($arrays,$val);
}
but the result always the first dimension make increment by that self
I already tried some func(like $arrays = $arrays+$val,array_push etc
) since 2 month ago I thought use array_merge is fine but the issue is make increment by that self so I am still not found the solution, I was also search on google and still no found about this.
Use one of the built-in array functions array_merge_recursive or array_replace_recursive. The code looks like:
$arrays = [];
foreach ($array as $val)
{
$arrays = array_replace_recursive($arrays,$val);
}
http://php.net/manual/en/function.array-merge-recursive.php
Related
I have two arrays:
$array_one = array('AA','BB','CC');
And:
$replacement_keys = array
(
""=>null,
"BFC"=>'john',
"ASD"=>'sara',
"CSD"=>'garry'
);
So far I've tried
array_combine and to make a loop and try to search for values but can't really find a solution to match the keys of the second array with the values of the first one and replace it.
My goal is to make a final output:
$new_array = array
(
''=>null,
'BB' => 'john',
'AA' => 'sara',
'CC' => 'garry'
);
In other words to find a matching first letter and than replace the key with the value of the first array.
Any and all help will be highly appreciated.
Here is a solution keeping both $replacement_keys and $array_one intact
$tempArray = array_map(function($value){return substr($value,0,1);}, $array_one);
//we will get an array with only the first characters
$new_array = [];
foreach($replacement_keys as $key => $replacement_key) {
$index = array_search(substr($key, 0, 1), $tempArray);
if ($index !== false) {
$new_array[$array_one[$index]] = $replacement_key;
} else {
$new_array[$key] = $replacement_key;
}
}
Here is a link https://3v4l.org/fuHSu
You can approach like this by using foreach with in_array
$a1 = array('AA','BB','CC');
$a2 = array(""=>null,"BFC"=>'john',"ASD"=>'sara',"CSD"=>'garry');
$r = [];
foreach($a2 as $k => $v){
$split = str_split($k)[0];
$split .= $split;
in_array($split, $a1) ? ($r[$split] = $v) : ($r[$k] = $v);
}
Working example :- https://3v4l.org/ffRWY
Suppose I have the array $array where:
$array[0] = {'a','b','c'}
$array[1] = {'d','e','f'}
And I want to iterate over the first column of the nested array in order to get 'a','d' only. What is the most efficient way to do that other than having a loop that iterates on $array[n][0]?
For PHP < 5.3 you can use array_map function like as
$array[0] = ['a','b','c'];
$array[1] = ['d','e','f'];
echo implode(',',array_map(function($v){ return $v[0];},$array));//a,d
As #Rizier123 commented you can simply use array_shift as callback function like as
echo implode(',',array_map('array_shift',$array));//a,d
Demo
Try this -
$array[0] = ['a','b','c'];
$array[1] = ['d','e','f'];
$new = array_column($array, 0);
foreach($new as $v) {
echo $v . ' ';
}
Output
a d
For lower versions of PHP -
$new = array();
foreach($array as $a) {
$new[] = $a[0];
}
Excuse me if this question was already solved. I've searched trough the site and couldn't find an answer.
I'm trying to build a bi-dimensional array from a string. The string has this structure:
$workers="name1:age1/name2:age2/name3:age3"
The idea is to explode the array into "persons" using "/" as separator, and then using ":" to explode each "person" into an array that would contain "name" and "age".
I know the basics about the explode function:
$array=explode("separator","$string");
But I have no idea how to face this to make it bidimensional. Any help would be appreciated.
Something like the following should work. The goal is to first split the data into smaller chunks, and then step through each chunk and further subdivide it as needed.
$row = 0;
foreach (explode("/", $workers) as $substring) {
$col = 0;
foreach (explode(":", $substring) as $value) {
$array[$row][$col] = $value;
$col++;
}
$row++;
}
$array = array();
$workers = explode('/', "name1:age1/name2:age2/name3:age3");
foreach ($workers as $worker) {
$worker = explode(':', $worker);
$array[$worker[0]] = $worker[1];
}
Try this code:
<?php
$new_arr=array();
$workers="name1:age1/name2:age2/name3:age3";
$arr=explode('/',$workers);
foreach($arr as $value){
$new_arr[]=explode(':',$value);
}
?>
The quick solution is
$results = [];
$data = explode("/", $workers);
foreach ($data as $row) {
$line = explode(":", $row);
$results[] = [$line[0], $line[1]];
}
You could also use array_walk with a custom function which does the second level split for you.
This is another approach, not multidimensional:
parse_str(str_replace(array(':','/'), array('=','&'), $workers), $array);
print_r($array);
Shorter in PHP >= 5.4.0:
parse_str(str_replace([':','/'], ['=','&'], $workers), $array);
print_r($array);
yet another approach, since you didn't really give an example of what you mean by "bidimensional" ...
$workers="name1:age1/name2:age2/name3:age3";
parse_str(rtrim(preg_replace('~name(\d+):([^/]+)/?~','name[$1]=$2&',$workers),'&'),$names);
output:
Array
(
[name] => Array
(
[1] => age1
[2] => age2
[3] => age3
)
)
I have this array in php,
$mainArray = array(
array("apple","two", "grren"),
array("samsung","five", "red"),
array("microsoft","one","gray"),
array("apple","nine", "blue"),
array("samsung","ten", "white"),
array("nokia","seven", "yellow")
);
I can easily loop through it and extract all the first entries of each array like this:
foreach($mainArray as $w => $n) {
$whatever = $mainArray[$w][0];
}
I'm trying to count how many entries are the same in the first element of each array, and have a result of something like:
apple (2)
samsung (2)
microsoft (1)
nokia (1)
I'm just not sure what is the correct way to do this.
Thank you in advance.
print_r(
array_count_values(
array_map('array_shift', $mainArray)
)
);
Output (Demo):
Array
(
[apple] => 2
[samsung] => 2
[microsoft] => 1
[nokia] => 1
)
So even I am a big fan of foreach, why did I not use it here?
First of all, to count values in an array, in PHP we have array_count_values. It does the job for us.
So the only problem left was to get all the first items into an array to count them with array_count_values. That is a typical mapping job, and I like mapping, too, next to foreach so I tried if array_map together with array_shift worked - and it did.
However you might want to look for a function called array_column. It's not yet available with PHP itself, but as PHP code in another answer:
$counts = array_count_values(array_column($mainArray, 0));
$count = array();
foreach($mainArray as $array) {
$first = $array[0];
if(!isset($count[$first])) $count[$first] = 0;
$count[$first]++;
}
print_r($count);
Collect every first element of the deep arrays by pushing them into a new array ($result in my example) and then call array_count_values() on that array. Like so:
$mainArray = array(
array("apple","two", "grren"),
array("samsung","five", "red"),
array("microsoft","one","gray"),
array("apple","nine", "blue"),
array("samsung","ten", "white"),
array("nokia","seven", "yellow")
);
$result = array();
foreach( $mainArray as $k => $v )
{
// let's continue if $v is not an array or is empty
if( !is_array( $v ) || empty( $v ) ) continue;
$result[] = $v[ 0 ];
}
var_dump( array_count_values( $result ) );
You can loop through the $mainArray to build a full array/list of values and then use array_count_values() on that:
$firstElements = array();
foreach ($mainArray as $arr) {
$firstElements[] = $arr[0];
}
$counts = array_count_values($firstElements);
Another option would be to loop through $mainArray and insert the value as an index for an array (if it doesn't already exist) and then increment it each time (this will do the same thing as array_count_values() in the end):
$counts = array();
foreach ($mainArray as $arr) {
if (!isset($counts[$arr[0]])) $counts[$arr[0]] = 0;
$counts[$arr[0]]++;
}
You can do it just like this:
foreach($mainArray as $n) {
$count[$n[0]] = isset($count[$n[0]]) ? $count[$n[0]]++ : 1;
}
var_dump($count); //should give you something like
/*
array(4) {
["apple"]=>
int(2)
["samsung"]=>
int(2)
["microsoft"]=>
int(1)
["nokia"]=>
int(1)
}
*/
I'm trying to figure out if its possible to loop a foreach loop in a array, and the loop result should be as the keys of the new array, like this,
$names = array('joe', 'piter', 'jack');
$dates = array('06/22/1987', '05/25/1988', '08/26/1990');
$arr = array();
foreach($names as $v){
$arr[] = $v;
}
$arr2 = array($arr => $dates);
print_r($arr2);
How do I do that?
Thnaks guys.
There is no need for a foreach loop to achieve that. Just use array_combine:
$names = array('joe', 'piter', 'jack');
$dates = array('06/22/1987', '05/25/1988', '08/26/1990');
$arr2 = array_combine($names, $dates);
print_r($arr2) Outputs:
Array
(
[joe] => 06/22/1987
[piter] => 05/25/1988
[jack] => 08/26/1990
)
In this situation you don't need to do this, but if you want to know how to use $v as a key for $arr2 in your loop you can just do the assignment in your loop:
$arr2[$v] = ...;
Well, saw #ascii-lime's answer (which is much better) after I typed this up, but just as an alternative I guess...
$names = array('joe', 'piter', 'jack');
$dates = array('06/22/1987', '05/25/1988', '08/26/1990');
$arr = array();
$i=0;
foreach($names as $v){
$arr[$v] = $dates[$i];
++$i;
}
print_r($arr);