$arrayA = Array (
[0] => 1,
[1] => 2,
[2] => 4
)
$arrayB = Array (
[1] => Dog,
[2] => Cat,
[3] => Cow,
[4] => Duck
)
How do I create an $arrayC that takes the value from the above 2 arrays:
$arrayC = Array (
[1] => Dog,
[2] => Cat,
[4] => Duck
)
Theoretically, it's something like this:
$arrayC = Array (
[$arrayA[0]] => $arrayB[$arrayA[0]],
[$arrayA[1]] => $arrayB[$arrayA[1]],
[$arrayA[2]] => $arrayB[$arrayA[2]]
)
Thanks.
You can do this in elegant way without foreach (Demo):
$arrayC = array_intersect_key($arrayB, array_flip($arrayA));
See array_intersect_key[Docs] and array_flip[Docs]
$arrayC = array();
foreach ($arrayA as $key) {
if (isset($arrayB[$key])) {
$arrayC[$key] = $arrayB[$key];
}
}
No need to write the foreach loop yourself:
//get only the keys that are in both
$arrayA = array_intersect_key(array_fill_keys($arrayA , true), $arrayB);
$arrayB = array_intersect_key($arrayB, $arrayA);
//combine the arrays
$arrayC = array_combine(array_keys($arrayA), $arrayB);
foreach($arrayA as $i => $key) {
$arrayC[$key] = $arrayB[$arrayA[$i]];
}
$arrayC will be:
Array ( [1] => Dog [2] => Cat [4] => Duck )
You can try to do something like this :-
foreach ($arrayA as $number)
{
if(isset($arrayB[$number])
{
$arrayC[$number] = $arrayB[$number];
}
}
Related
I got string like 1_2_3_4_5 and I want an array like this:
array(
[0] = 1
[1] = 1_2
[2] = 1_2_3
[3] = 1_2_3_4
[4] = 1_2_3_4_5
)
Any idea for a oneliner?
just for fun using substr
$st = '1_2_3_4_5';
$num[]=$st;
while($pos=strrpos($st,'_')){
$num[]=$st=substr($st,0,$pos);
}sort($num);
print_r($num);
Output
(
[0] => 1
[1] => 1_2
[2] => 1_2_3
[3] => 1_2_3_4
[4] => 1_2_3_4_5
)
<?php
$input = '1_2_3_4_5';
// Get an array with 1, 2, 3, 4 and 5
$parts = explode('_', $input);
$output = [];
$i = 1;
foreach ($parts as $part) {
// array_slice() will take 1 to n elements from the array of numbers
$values = array_slice($parts, 0, $i++);
// Join the values
$output[] = implode('_', $values);
}
print_r($output);
It will show this:
Array
(
[0] => 1
[1] => 1_2
[2] => 1_2_3
[3] => 1_2_3_4
[4] => 1_2_3_4_5
)
Try it at 3V4L.
I have two arrays with same amount of values. I need to combine them ( array1 value to key, array2 value as value) without losing the values of the second array due to duplicate key. when I use combine_array() as expected it just gets the last value of the second array with the same key.
Array
(
[0] => 1
[1] => 2
[2] => 2
[3] => 3
)
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
Desired result
Array
(
[1] => 1
[2] => Array(
[0]=>2
[1]=>3
)
[3] => 2
)
This code will meet your request
$array1 = array("0"=>1,"1"=>2,"2"=>2,"3"=>3);
$array2 = array("0"=>1,"1"=>2,"2"=>3,"3"=>4);
$array = array();
foreach($array1 as $key => $value){
if($value != $array2[$key]){
$array[$key][] = $value;
$array[$key][] = $array2[$key];
}else{
$array[$key] = $value;
}
}
print_r($array);
The desired result is
Array
(
[0] => 1
[1] => 2
[2] => Array
(
[0] => 2
[1] => 3
)
[3] => Array
(
[0] => 3
[1] => 4
)
)
I'm sure there are way better solutions than this, but it does the job for now. I would appreciate if someone can send a better written solution.
$combined = array();
$tempAr = array();
$firstMatch = array();
$count = 0;
foreach ($array1 as $index => $key) {
if (array_key_exists($key, $combined)) {
$tempAr[] = $array2[$index];
$count++;
} else {
$totalCount = $count;
}
if (!array_key_exists($key, $firstMatch)) {
$firstMatch[$key] = $array2[$index];
}
$output = array_slice($tempAr, $totalCount);
$combined[$key] = $output;
}
$combined = array_merge_recursive($firstMatch, $combined);
I have 3 arrays as below.
$array1 = Array
(
[0] => 05/01
[1] => 05/02
)
$array2 =Array
(
[0] => ED
[1] => P
)
$array3 =Array
(
[0] => Mon
[1] => Tue
)
I want to merge these 3 arrays as below $result_array. I have written a code as below. But It gave a empty array.
$result_array =Array
(
[0] => Array
(
[0] => 05/01
[1] => ED
[2] => Mon
)
[1] => Array
(
[0] => 05/02
[1] => P
[2] => Tue
)
)
Code:
for($z=0; $z<count($array1); $z++){
$all_array[$z][] = array_merge($array1[$z],$array2[$z] );
$all_array2[$z] = array_merge($all_array[$z],$array3[$z] );
}
Please help me to do this.
Simply foreach over the first array and use the index as the key to the other arrays.
foreach ( $array1 as $idx => $val ) {
$all_array[] = [ $val, $array2[$idx], $array3[$idx] ];
}
Remember this will only work if all 3 arrays are the same length, you might like to check that first
You can simply walk through the first array with a foreach loop then access the corresponding arrays and combine the results into one big array. This will only work if the arrays are the same length so it's worth checking that before to stop any errors. Something like this:
<?php
$arr1 = ['05/01', '05/02'];
$arr2 = ['ED', 'P'];
$arr3 = ['Mon', 'Tue'];
$combined = [];
if (count($arr1) != count($arr2) || count($arr1) != count($arr3))
die("Array lengths do not match!");
foreach ($arr1 as $key => $val) {
$combined[] = [$val, $arr2[$key], $arr3[$key]];
}
var_dump($combined);
You can see an eval.in of this working here - https://eval.in/833893
Create an sample array and push to each array value with respective key
$sample = array();
for($z=0; $z<count($array1); $z++){
$sample[]=array($array1[$z],$array2[$z],$array3[$z]);
}
print_r($sample);
Out put is
Array ( [0] => Array (
[0] => 05/01
[1] => ED
[2] => Mon
)
[1] => Array (
[0] => 05/02
[1] => P
[2] => Tue
)
)
this work for n of arrays and dynamic length of array
function mergeArrays(...$arrays)
{
$length = count($arrays[0]);
$result = [];
for ($i=0;$i<$length;$i++)
{
$temp = [];
foreach ($arrays as $array)
$temp[] = $array[$i];
$result[] = $temp;
}
return $result;
}
$x = mergeArrays(['05/01' , '05/02'] , ['ED' , 'P'] , ['Mon' , 'Tus']);
$y = mergeArrays(['05/01' , '05/02' , 'X'] , ['ED' , 'P' , 'Y'] , ['Mon' , 'Tus' , 'Z'] , ['A' , 'B' , 'C']);
var_dump($x);
var_dump($y);
function merge($file_name, $titles, $description)
{
$result = array();
foreach($file_name as $key=>$name )
{
$result[] = array( 'file_name' => $name, 'title' => $titles[$key],
'description' => $description[ $key ] );
}
return $result;
}
$array1 = Array
(
'05/01',
'05/02'
);
$array2 = Array
(
'ED',
'P'
);
$array3 =Array
(
'Mon',
'Tue'
);
$result_array = array();
foreach ($array1 as $key=>$val)
{
$result_array[$key] = array($array1[$key],$array2[$key],$array3[$key]);
}
echo "<PRE>"; print_r($result_array);
I need to combine 2 arrays under the same key by appending Array2 to Array1:
Array1
(
[0] => value1
[1] => value2
[2] => value3
[3] => value4
[4] => value5
[5] => value6
[6] => value7
)
Array2
(
[0] => add1
[1] => add2
[2] => add3
[3] => add4
[4] => add5
[5] => add6
[6] => add7
)
so that Array3 looks like this:
Array1
(
[0] => value1add1
[1] => value2add2
[2] => value3add3
[3] => value4add4
[4] => value5add5
[5] => value6add6
[6] => value7add7
)
I searched through php.net but I wasn't able to find anything. Any help would be much appreciated! Thank you in advance for your input.
array_mapdocs makes looping superfluous in this case:
$arr1 = array('value1','value2','value3');
$arr2 = array('add1','add2','add3');
$merged = array_map(function($x, $y) { return $x . $y; }, $arr1, $arr2);
If you don't have PHP5.3+ (or you don't like lambda) you'll need to define the closure in a separate function and reference that function's name instead inside your array_map call.
Just do a loop:
if (count($arr1) == count($arr2))
{
$arr3 = array();
foreach ($arr1 as $key => $val)
$arr3 = $val . $arr2[$key];
}
else
{
echo "Arrays should be of same size!";
$arr3 = array();
for ($i = 0, $i < min(count($arr1),count($arr2)); $i++)
$arr3 = $arr1[$i] . $arr2[$i];
}
(Exact implementation should depend on your input values)
Soemthing like this:
foreach($array1 as $k=> $value){
$array3[$k] = $value . $array2[$k];
}
print_r($array3);
Mind you, it will only take as many items as $array1 contains. If $array2 is larger, other values will be ignored.
I have an array like this:
Array (
[0] => ing_1_ing
[1] => ing_1_amount
[2] => ing_1_det
[3] => ing_1_meas
[4] => ing_2_ing
[5] => ing_2_amount
[6] => ing_2_det
[7] => ing_2_meas
)
And I want to group the values into an array like this:
Array (
[0] => Array(
[0] => ing_1_ing
[1] => ing_1_amount
[2] => ing_1_det
[3] => ing_1_meas
)
[1] => Array(
[0] => ing_2_ing
[1] => ing_2_amount
[2] => ing_2_det
[3] => ing_2_meas
)
)
There may be many other items named like that: ing_NUMBER_type
How do I group the first array to the way I want it? I tried this, but for some reason, strpos() sometimes fails:
$i = 1;
foreach ($firstArray as $t) {
if (strpos($t, (string)$i)) {
$secondArray[--$i][] = $t;
} else {
$i++;
}
}
What is wrong? Can you advice?
It depends what you are trying to achieve, if you want to split array by chunks use array_chunk method and if you are trying to create multidimensional array based on number you can use sscanf method in your loop to parse values:
$result = array();
foreach ($firstArray as $value)
{
$n = sscanf($value, 'ing_%d_%s', $id, $string);
if ($n > 1)
{
$result[$id][] = $value;
}
}
<?php
$ary1 = array("ing_1_ing","ing_1_amount","ing_1_det","ing_1_meas","ing_2_ing","ing_2_amount","ing_2_det","ing_2_meas");
foreach($ary1 as $val)
{
$parts = explode("_",$val);
$ary2[$parts[1]][]=$val;
}
?>
This creates:
Array
(
[1] => Array
(
[0] => ing_1_ing
[1] => ing_1_amount
[2] => ing_1_det
[3] => ing_1_meas
)
[2] => Array
(
[0] => ing_2_ing
[1] => ing_2_amount
[2] => ing_2_det
[3] => ing_2_meas
)
)
What I'd do is something like this:
$result = array();
foreach ($firstArray as $value)
{
preg_match('/^ing_(\d+)_/', $value, $matches);
$number = $matches[1];
if (!array_key_exists($number, $result))
$result[$number] = array();
$result[$number][] = $value;
}
Basically you iterate through your first array, see what number is there, and put it in the right location in your final array.
EDIT. If you know you'll always have the numbers start from 1, you can replace $number = $matches[1]; for $number = $matches[1] - 1;, this way you'll get exactly the same result you posted as your example.