Merge array values for same keys inside loop with php - php

Going through foreach loop for filter on my site I get array back like this:
Array
(
[21] => Blau
[24] => Azul
[28] => Blue
)
By choosing next filter another array will be created:
Array
(
[21] => Grün
[24] => Verde
[28] => Green
)
and so on...
What I what to do is merge values of these arrays on same keys. So it have to be look like this:
Array
(
[21] => Blau-Grün
[24] => Azul-Verde
[28] => Blue-Green
)
It worked with Uchiha's code. I made some changed inside my loop:
foreach (...){
//some logic before
$array[] = array();
$i = 0;
foreach($array as $k => $v){
$i++;
foreach($array[$k] as $key => $value){
if(array_key_exists($key, $array[$i])){
$result[$key] = $value . '-' . $array[$i][$key];
}
}
}
echo '<pre>' . print_r($result,true) . '</pre>';
}

$maxItems = max(count($blue),count($green));
for ($i = 0; $i < $maxItems; $i++) {
if (isset($blue[$i], $green[$i])) {
$combined[$i] = $blue[$i].'-'.$green[$i];
} else {
if (isset($blue[$i])) {
$combined[$i] = $blue[$i];
} else {
$combined[$i] = $green[$i];
}
}
}

You can use foreach along with array_key_exists as
foreach($arr1 as $key => $value){
if(array_key_exists($key, $arr2)){
$result[$key] = $value.'-'.$arr2[$key];
}
}
Fiddle

you can use array_map with a closure that joins the two values, e.g.
$joined = array_map(function($m, $n){ return $m . '-' . $n; }, $array1, $array2);

$foo = array(1 => "Bob", 2 => "Sepi");
$bar = array(1 => "sach", 2 => "john");
$foobar= array();
foreach ($foo as $key => $value) {
foreach ($bar as $key1 => $value1) {
if($key == $key1){
$foobar[] = $value."-".$value1;
}
}}

You can create a function, which takes both of arrays as parameter and identify which one has more elements, loop through and concat the string from another array at the same key.
$array1 = array(
'Blau',
'Azul',
'Blue'
);
$array2 = array(
'Grün',
'Verde',
'Green'
)
function mergeArray($array1, $array2){
$newArray = array();
if(count($array1) >= count($array2)){
foreach($array1 as $key => $value){
$newArray[] = $value . (array_key_exists($key, $array2) ? '-' . $array2[$key] : '');
}
} else {
foreach($array2 as $key => $value){
$newArray[] = $value . (array_key_exists($key, $array1) ? '-' . $array1[$key] : '');
}
}
}
$newArray = mergeArray($array1, $array2);
$newArray contains the result you expected.

here is simple and tested code
<?php
$a1=array(
1 => 'Blau',
2 => 'Azul',
3 => 'Blue'
);
$a2=array
(
1 => 'Grün',
2 => 'Verde',
4 => 'Green'
);
$a3=$a1 + $a2;
$a4=$a2 + $a1;
foreach($a3 as $key=>$val){
if($a4[$key] != $a3[$key]){
$a3[$key] = $a3[$key].' '.$a4[$key];
}
}
print_r($a3);
?>

Related

Get only Numeric values from Array in PHP

I have an array that looks something like this:
Array (
[0] => Array ( [country_percentage] => 5 %North America )
[1] => Array ( [country_percentage] => 0 %Latin America )
)
I want only numeric values from above array. I want my final array like this
Array (
[0] => Array ( [country_percentage] => 5)
[1] => Array ( [country_percentage] => 0)
)
How I achieve this using PHP?? Thanks in advance...
When the number is in first position you can int cast it like so:
$newArray = [];
foreach($array => $value) {
$newArray[] = (int)$value;
}
I guess you can loop the 2 dimensional array and use a preg_replace, i.e.:
for($i=0; $i < count($arrays); $i++){
$arrays[$i]['country_percentage'] = preg_replace( '/[^\d]/', '', $arrays[$i]['country_percentage'] );
}
Ideone Demo
Update Based on your comment:
for($i=0; $i < count($arrays); $i++){
if( preg_match( '/North America/', $arrays[$i]['country_percentage'] )){
echo preg_replace( '/[^\d]/', '', $arrays[$i]['country_percentage'] );
}
}
Try this:
$arr = array(array('country_percentage' => '5 %North America'),array("country_percentage"=>"0 %Latin America"));
$result = array();
foreach($arr as $array) {
$int = filter_var($array['country_percentage'], FILTER_SANITIZE_NUMBER_INT);
$result[] = array('country_percentage' => $int);
}
Try this one:-
$arr =[['country_percentage' => '5 %North America'],
['country_percentage' => '0 %Latin America']];
$res = [];
foreach ($arr as $key => $val) {
$res[]['country_percentage'] = (int)$val['country_percentage'];
}
echo '<pre>'; print_r($res);
output:-
Array
(
[0] => Array
(
[country_percentage] => 5
)
[1] => Array
(
[country_percentage] => 0
)
)
You can use array_walk_recursive to do away with the loop,
passing the first parameter of the callback as a reference to modify the initial array value.
Then just apply either filter_var or intval as already mentioned the other answers.
$array = [
["country_percentage" => "5 %North America"],
["country_percentage" => "0 %Latin America"]
];
array_walk_recursive($array, function(&$value,$key){
$value = filter_var($value,FILTER_SANITIZE_NUMBER_INT);
// or
$value = intval($value);
});
print_r($array);
Will output
Array
(
[0] => Array
(
[country_percentage] => 5
)
[1] => Array
(
[country_percentage] => 0
)
)
You could get all nemeric values by looping through the array. However I don't think this is the most efficient and good looking answer, I'll post it anyways.
// Array to hold just the numbers
$newArray = array();
// Loop through array
foreach ($array as $key => $value) {
// Check if the value is numeric
if (is_numeric($value)) {
$newArray[$key] = $value;
}
}
I missunderstood your question.
$newArray = array();
foreach ($array as $key => $value) {
foreach ($value as $subkey => $subvalue) {
$subvalue = trim(current(explode('%', $subvalue)));
$newArray[$key] = array($subkey => $subvalue);
}
}
If you want all but numeric values :
$array[] = array("country_percentage"=>"5 %North America");
$array[] = array("country_percentage"=>"3 %Latin America");
$newArray = [];
foreach ($array as $arr){
foreach($arr as $key1=>$arr1) {
$newArray[][$key1] = intval($arr1);
}
}
echo "<pre>";
print_R($newArray);
This is kind of a ghetto method to doing it cause I love using not as many pre made functions as possible. But this should work for you :D
$array = array('jack', 2, 5, 'gday!');
$new = array();
foreach ($array as $item) {
// IF Is numeric (each item from the array) will insert into new array called $new.
if (is_numeric($item)) { array_push($new, $item); }
}

Determine whether array key value is blank

I have an array like below, as you can see the last array [adad] value is blank, how can I write an if statement to tell whether this is blank.
Array
(
[K] => Array
(
[0] => mabel__chan
[1] => mabel chan
)
[B] => Array
(
[0] => kieron br
)
[C] => Array
(
[0] => a br
[1] => a
)
[adad] => Array
(
[0] =>
)
)
I have tried doing this
if (count(array_filter($array)) == 0) {}
Pseudo code
if(array[key] == blank) {
echo "is blank";
} else {
echo "isn't blank";
}
**PHP Script this is how I get my data from mongoDB*
The answer below is working correctly when I use echos but now when I'm trying to push into new arrays its broken somewhere I get no data back anymore.
$col = "A" . $user->agencyID;
$db = $m->rules;
$collection = $db->$col;
$id = $_POST['ruleID'];
$search = array(
'_id' => new MongoId($id)
);
$cursor = $collection->find($search);
$validTagsArray = array();
$validArray = array();
foreach ($cursor as $key => $value) {
$temp = array_walk($array, function($v, $k) {
if (count(array_filter($v)) === 0) {
foreach ($value['AutoFix'] as $keyTwo => $valTwo) {
$x = 0;
$validTagsArray['data'][] = array($keyTwo, $x);
}
} else {
foreach ($value['AutoFix'] as $keyTwo => $valTwo) {
$x = 0;
foreach ($valTwo as $key => $value) {
$x++;
}
$validTagsArray['data'][] = array($keyTwo, $x);
}
}
});
}
echo json_encode($validTagsArray);
You can try this -
$array = array
(
'K' => array('0' => 'mabel__chan','1' => 'mabel chan'),
'B' => array('0' => 'kieron br'),
'C' => array('0' => 'a br', '1' => 'a'),
'adad' => array('0' => '')
);
$temp = array_walk($array, function($v, $k) {
if(count(array_filter($v)) === 0) { // check the count of non-empty elements in the sub array
echo $k . ' is empty';
}
});
Output
adad is empty
You can write as:
if([adad][0]== " ")
{
}
You can also try this :
foreach($array as $key=>$value){
if(empty($value))
echo "empty";
}

combine arrays and concat value?

Little complex to explain , so here is simple concrete exemple :
array 1 :
Array
(
[4] => bim
[5] => pow
[6] => foo
)
array 2 :
Array
(
[n] => Array
(
[0] => 1
)
[m] => Array
(
[0] => 1
[1] => 2
)
[l] => Array
(
[0] => 1
[1] => 4
[2] => 64
)
And i need to output an array 3 ,
array expected :
Array
(
[bim] => n-1
[pow] => Array
(
[0] => m-1
[1] => m-2
)
[foo] => Array
(
[0] => l-1
[1] => l-4
[2] => l-64
)
Final echoing OUTPUT expected:
bim n-1 , pow m-1 m-2 ,foo l-1 l-4 l-64 ,
I tried this but seems pity:
foreach($array2 as $k1 =>$v1){
foreach($array2[$k1] as $k => $v){
$k[] = $k1.'_'.$v);
}
foreach($array1 as $res =>$val){
$val = $array2;
}
Thanks for helps,
Jess
CHALLENGE ACCEPTED
<?php
$a = array(
4 => 'bim',
5 => 'pow',
6 => 'foo',
);
$b = array(
'n' => array(1),
'm' => array(1, 2),
'l' => array(1, 4, 64),
);
$len = count($a);
$result = array();
$aVals = array_values($a);
$bKeys = array_keys($b);
$bVals = array_values($b);
for ($i = 0; $i < $len; $i++) {
$combined = array();
$key = $aVals[$i];
$prefix = $bKeys[$i];
$items = $bVals[$i];
foreach ($items as $item) {
$combined[] = sprintf('%s-%d', $prefix, $item);
};
if (count($combined) === 1) {
$combined = $combined[0];
}
$result[$key] = $combined;
}
var_dump($result);
?>
Your code may be very easy. For example, assuming arrays:
$one = Array
(
4 => 'bim',
5 => 'pow',
6 => 'foo'
);
$two = Array
(
'n' => Array
(
0 => 1
),
'm' => Array
(
0 => 1,
1 => 2
),
'l' => Array
(
0 => 1,
1 => 4,
2 => 64
)
);
You may get your result with:
$result = [];
while((list($oneKey, $oneValue) = each($one)) &&
(list($twoKey, $twoValue) = each($two)))
{
$result[$oneValue] = array_map(function($item) use ($twoKey)
{
return $twoKey.'-'.$item;
}, $twoValue);
};
-check this demo Note, that code above will not make single-element array as single element. If that is needed, just add:
$result = array_map(function($item)
{
return count($item)>1?$item:array_shift($item);
}, $result);
Version of this solution for PHP4>=4.3, PHP5>=5.0 you can find here
Update: if you need only string, then use this (cross-version):
$result = array();
while((list($oneKey, $oneValue) = each($one)) &&
(list($twoKey, $twoValue) = each($two)))
{
$temp = array();
foreach($twoValue as $item)
{
$temp[] = $twoKey.'-'.$item;
}
$result[] = $oneValue.' '.join(' ', $temp);
};
$result = join(' ', $result);
As a solution to your problem please try executing following code snippet
<?php
$a=array(4=>'bim',5=>'pow',6=>'foo');
$b=array('n'=>array(1),'m'=>array(1,2),'l'=>array(1,4,64));
$keys=array_values($a);
$values=array();
foreach($b as $key=>$value)
{
if(is_array($value) && !empty($value))
{
foreach($value as $k=>$val)
{
if($key=='n')
{
$values[$key]=$key.'-'.$val;
}
else
{
$values[$key][]=$key.'-'.$val;
}
}
}
}
$result=array_combine($keys,$values);
echo '<pre>';
print_r($result);
?>
The logic behind should be clear by reading the code comments.
Here's a demo # PHPFiddle.
//omitted array declarations
$output = array();
//variables to shorten things in the loop
$val1 = array_values($array1);
$keys2 = array_keys($array2);
$vals2 = array_values($array2);
//iterating over each element of the first array
for($i = 0; $i < count($array1); $i++) {
//if the second array has multiple values at the same index
//as the first array things will be handled differently
if(count($vals2[$i]) > 1) {
$tempArr = array();
//iterating over each element of the second array
//at the specified index
foreach($vals2[$i] as $val) {
//we push each element into the temporary array
//(in the form of "keyOfArray2-value"
array_push($tempArr, $keys2[$i] . "-" . $val);
}
//finally assign it to our output array
$output[$val1[$i]] = $tempArr;
} else {
//when there is only one sub-element in array2
//we can assign the output directly, as you don't want an array in this case
$output[$val1[$i]] = $keys2[$i] . "-" . $vals2[$i][0];
}
}
var_dump($output);
Output:
Array (
["bim"]=> "n-1"
["pow"]=> Array (
[0]=> "m-1"
[1]=> "m-2"
)
["foo"]=> Array (
[0]=> "l-1"
[1]=> "l-4"
[2]=> "l-64"
)
)
Concerning your final output you may do something like
$final = "";
//$output can be obtained by any method of the other answers,
//not just with the method i posted above
foreach($output as $key=>$value) {
$final .= $key . " ";
if(count($value) > 1) {
$final .= implode($value, " ") .", ";
} else {
$final .= $value . ", ";
}
}
$final = rtrim($final, ", ");
This will echo bim n-1, pow m-1 m-2, foo l-1 l-4 l-64.

same values from php array in new array

i have a problem with arrays, there are not my friends :)
i have a this array:
Array
(
[0] => 2012163115
[1] => 2012163115
[2] => 2012161817
[3] => 201214321971
[4] => 201214321971
[5] => 201214321971
)
and i need this with all the variables appear more than once
Array
(
[0] => 2012163115
[1] => 201214321971
)
i try this
foreach ($array as $val) {
if (!in_array($val, $array_temp)) {
$array_temp[] = $val;
} else {
array_push($duplis, $val);
}
}
but the result is
Array
(
[0] => 2012163115
[1] => 201214321971
[2] => 201214321971
)
where is my mistake? thanks for help!
array_unique() is there for you.
EDIT: ops I didn't notice the "more than once" clause, in that case:
$yourArray = array('a', 'a', 'b', 'c');
$occurrences = array();
array_walk($yourArray, function($item) use(&$occurrences){
$occurrences[$item]++;
});
$filtered = array();
foreach($occurrences as $key => $value){
$value > 1 && $filtered[] = $key;
}
var_dump($filtered);
$array = array(
'2012163115',
'2012163115',
'2012161817',
'201214321971',
'201214321971',
'201214321971',
);
$duplication = array_count_values($array);
$duplicates = array();
array_walk($duplication, function($key, $value) use (&$duplicates){
if ($key > 1)
$duplicates[] = $value;
});
var_dump($duplicates);
Please see http://php.net/manual/en/function.array-unique.php#81513
These are added characters to make SO accept the post!
$array_counting = array();
foreach ($array as $val)
if ( ! in_array($val, $array_counting))
{
$array_counting[$val] ++; // counting
}
$array_dups = array();
foreach ($array_counting as $key => $count)
{
if ($count > 1)
$array_dups[] = $key; // this is more than once
}

php, manipulate arrays, combine array, associative

I have an array like
$array = Manufacturer => BMW
Miles => 10000
and I would like to use this to create a new array with a specific name/value like this :
$array = st_selval_0_0 => Manufacturer
st_tmdata_0_0 => BMW
st_selval_0_1 => Miles
st_tmdata_0_1 => 10000
As you can see the last digit must increase on each new name=>value.
$result = array();
$i = 0;
foreach($array as $key => $val) {
$result['st_selval_0_'.$i] = $key;
$result['st_tmdata_0_'.$i] = $val;
$i++;
}
See also foreach in the manual.
$newArray = array();
$i=0;
foreach($array as $k => $v)
{
$newArray["st_selval_0_$i"] = $k;
$newArray["st_tmdata_0_$i"] = $v;
$i++;
}
$input = array('Manufacturer' => 'BMW', 'Miles' => 10000);
$output = array();
$i = 0;
foreach ($input as $key => $value) {
$output['st_selval_0_' . $i] = $key;
$output['st_tmdata_0_' . $i] = $value;
$i++;
}
print_r($output);
Output:
Array
(
[st_selval_0_0] => Manufacturer
[st_tmdata_0_0] => BMW
[st_selval_0_1] => Miles
[st_tmdata_0_1] => 10000
)

Categories