I have 2 arrays
$array1 = array(22,193,124);
$array2 = array(array('id'=>22, 'count'=> 1), array('id'=>124, 'count'=>2));
Now I need to search in $array2 for id from $array1 and if found to increment the count value and also add to the array the one's which are not found with a count as 1 so my resulting array would be
$arr = array(array('id'=>22, 'count'=> 2), array('id'=>124, 'count'=>3), array('id'=>193, 'count'=>1));
any help would be appreciated
The current code which I tried is
if($array2){
foreach($array1 as $array){
if(in_array($array, array_column($array2, 'id'))){
$wa_array['count'] += 1;
} else {
$wa_array['id'] = $array;
$wa_array['count'] = 1;
}
}
} else {
foreach($array1 as $array){
$wa_array['id'] = $array;
$wa_array['count'] = 1;
}
}
This may be something you are looking for -
$array1 = array(22,193,124);
$array2 = array(array('id'=>22, 'count'=> 1), array('id'=>124, 'count'=>2));
foreach($array1 as $key=>$digit)
{
$keyFound = array_search($digit, array_column($array2, 'id'));
if($keyFound === false)
{
array_push($array2, ['id'=>$digit, 'count'=>1]);
}
else
{
$array2[$keyFound]['count']++;
}
}
print_r($array2);
The question is not so clear, so I will go with my understanding : You need to check if values inside the first array are in the second array. If yes, increment the count value of that second array, if not, create that element with the value of 1.
This code is not tested, hope this can help find the good solution.
foreach($array1 as $value){
searchForId($value,$array2);
}
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['id'] === $id) {
$val['count'] += 1;
}else{
array_push(array('id'=>$id,'count'=>1))
}
}
return null;
}
you should loop through $array2, not $array1. Finding the value in array_column($array2, 'id') doesn't tell you the index of the array element to increment.
foreach ($array2 as &$item) {
if (in_array($item['id'], $array1)) {
$item['count']++;
}
}
Note that you have to use &$item to make this a reference to the original array element, so that modifying it will update $array2. Otherwise, $item would be a copy of the array element.
If $array1 is large, it would be better to convert it to an associative array so you can test membership more efficiently.
$array1_assoc = array_flip($array1);
Then the test in the loop becomes:
if (isset($array1_assoc[$item['id']]) {
Check this one. NOTE: But this has O(n^2) complexity.
$array1 = [22,193,124];
$array2 = [['id'=>22, 'count'=> 1], ['id'=>124, 'count'=>2]];
foreach ($array1 as $value) {
$isFound = false;
foreach ($array2 as &$item) {
if ($value == $item['id']) {
$item['count']++;
$isFound = true;
continue;
}
}
if ($isFound == false) {
$array2 [] = ['id'=>$value, 'count'=> 1];
}
}
var_dump($array2);
Related
I would like to build $goal array from $initial only. Any ideas? Thank you
Edit : the question could be how to differentiate associative parts from sequential ones.
$intial=[
"one",
"two"=>"myTwo",
"three",
"four"=>"myFour"
];
$goal=[
"one"=>null,
"two"=>"myTwo",
"three"=>null,
"four"=>"myFour"
];
The 'sequential' parts will have numeric keys, so if your 'associative' keys will always be strings, you could use that to differentiate:
$goal = [];
foreach ($initial as $key => $value) {
if (is_numeric($key)) {
$goal[$value] = null;
} else {
$goal[$key] = $value;
}
}
$goal = [];
foreach($initial as $key => $val){
if(isset($val){
$goal[$key] = $val;
}else{
$goal[$key] = $key;
}
}
I am stuck on something that might be very simple.
I am creating a new array by looping through an existing array using a recursion function yet I can not seem to get the values to stick to the new array. The function, in the end, will be a bit more complex, but for now I need some help.
I have tried soooo many ways to get this to work but I am at a loss right now.
Here is my php function
function recursive($array) {
$newArray = array();
foreach($array as $key => $value) {
if(is_array($value)){
recursive($value);
}else{
$newArray[] = $value;
}
}
return $newArray;
}
As is, the new array never gets filled...BUT, if I change this line...
recursive($value); // Why can't I just call the recursive function here?
...to...
$newArray[] = recursive($value); // Instead of having to set a new value to the new array?
everything works properly...except that my goal was to create a flat array with only the values.
So my question is, why is it necessary to set a new array value in order to call the recursive function again? Ideally, I want to skip setting a new array value if the value is an array and just continue the loop through the original array.
Use array_merge:
function recursive($array) {
$newArray = array();
foreach($array as $key => $value) {
if(is_array($value)){
$newArray = array_merge($newArray, recursive($value));
}else{
$newArray[] = $value;
}
}
return $newArray;
}
...or you could use special operator:
function recursive($array) {
$newArray = array();
foreach($array as $key => $value) {
if(is_array($value)){
$newArray += recursive($value);
}else{
$newArray[] = $value;
}
}
return $newArray;
}
...or pass a variable by reference like this:
function recursive($array, &$newArray = null) {
if (!$newArray) {
$newArray = array();
}
foreach($array as $key => $value) {
if(is_array($value)){
recursive($value, $newArray);
}else{
$newArray[] = $value;
}
}
return $newArray;
}
use array_merge() to merge the array returned from recursive($value); and $newArray
$newArray = array_merge($newArray,recursive($value));
You can guarantee that $newArray will be flat after this, as the previous value of $newArray was flat, and recursive always returns a flat array, so the combination of both should be a flat array.
You aren't doing anything with the return from your recursive function. Try this:
function recursive($array) {
$newArray = array();
foreach($array as $key => $value) {
if(is_array($value)){
// This is what was modified
$newArray = array_merge($newArray, recursive($value));
}else{
$newArray[] = $value;
}
}
return $newArray;
}
I've stuck in some certain problem, I've got two arrays which are the output of some other methods:
$firstArray = ['Johny Mao'=>'A', 'Kate Young'=>'B', 'Adam Mink'=>'C'];
$secondArray = [
['Johny Mao','A'],
['Kate Young', 'B'],
['Adam Mink', 'C']
];
How should I change these two arrays in order two compare them?
I need to know wheter they consist the same information.
Probably I should use array_diff methods but first I need to change arrays structure to be able to compar them.
Hope expressed clearly :)
Create a new array (or modify the second array) to key/value pairs matching the first array
$newArray = array_combine(
array_column($secondArray, 0),
array_column($secondArray, 1)
);
and then do your comparison
The comments are spot on. This is the developers idea.
Without using array_diff or something:
function array_are_same($firstarray,$secondarray){
foreach ($firstarray as $key => $value) {
if (!array_key_exists($key, $secondarray)
|| $secondarray[$key] !== $value){
return false;
}
return true;
}
}
You could do something like this, assuming you don't need to check if elements in first array aren't in second array.
function areArraysEqual($firstArray, $secondArray)
{
if(count($firstArray) != count($secondArray))
{
return false;
}
foreach($secondArray as $key => $value)
{
if(!isset($firstArray[$value[0]]) || $firstArray[$value[0]] != $value[1])
{
return false;
}
}
return true;
}
$firstArray = ['Johny Mao'=>'A', 'Kate Young'=>'B', 'Adam Mink'=>'C'];
$secondArray = [
['Johny Mao','A'],
['Kate Young', 'B'],
['Adam Mink', 'C']
];
$result = areArraysEqual($firstArray, $secondArray);
var_dump($result);
Edit:
This code below should now take into account if elements in the first array aren't in the second array.
<?php
function isValueIn2dArray(&$array, $secondDimensionKey, $value)
{
foreach($array as $key => $array2)
{
if($array2[$secondDimensionKey] == $value)
{
return true;
}
}
return false;
}
function areArraysEqual($firstArray, $secondArray)
{
if(count($firstArray) != count($secondArray))
{
return false;
}
foreach($secondArray as $key => $value)
{
if(!isset($firstArray[$value[0]]) || $firstArray[$value[0]] != $value[1])
{
return false;
}
}
foreach($firstArray as $key => $value)
{
if(!isValueIn2dArray($secondArray, 0, $key))
{
return false;
}
}
return true;
}
$firstArray = ['Johny Mao'=>'A', 'Kate Young'=>'B', 'Adam Mink'=>'C'];
$secondArray = [
['Johny Mao','A'],
['Kate Young', 'B'],
['Adam Mink', 'C']
];
$result = areArraysEqual($firstArray, $secondArray);
var_dump($result);
I need compare 2 arrays , the first array have one order and can´t change , in the other array i have different values , the first array must compare his id with the id of the other array , and if the id it´s the same , take the value and replace for show all in the same order
For Example :
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
The Result in this case i want get it´s this :
"1a-dogs","2a-cats","3a-birds","4a-walking"
If the id in this case 4a it´s the same , that entry must be modificate and put the value of other array and stay all in the same order
I do this but no get work me :
for($fte=0;$fte<count($array_1);$fte++)
{
$exp_id_tmp=explode("-",$array_1[$fte]);
$cr_temp[]="".$exp_id_tmp[0]."";
}
for($ftt=0;$ftt<count($array_2);$ftt++)
{
$exp_id_targ=explode("-",$array_2[$ftt]);
$cr_target[]="".$exp_id_targ[0]."";
}
/// Here I tried use array_diff and others but no can get the results as i want
How i can do this for get this results ?
Maybe you could use the array_udiff_assoc() function with a callback
Here you go. It's not the cleanest code I've ever written.
Runnable example: http://3v4l.org/kUC3r
<?php
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
function getKeyStartingWith($array, $startVal){
foreach($array as $key => $val){
if(strpos($val, $startVal) === 0){
return $key;
}
}
return false;
}
function getMergedArray($array_1, $array_2){
$array_3 = array();
foreach($array_1 as $key => $val){
$startVal = substr($val, 0, 2);
$array_2_key = getKeyStartingWith($array_2, $startVal);
if($array_2_key !== false){
$array_3[$key] = $array_2[$array_2_key];
} else {
$array_3[$key] = $val;
}
}
return $array_3;
}
$array_1 = getMergedArray($array_1, $array_2);
print_r($array_1);
First split the 2 arrays into proper key and value pairs (key = 1a and value = dogs). Then try looping through the first array and for each of its keys check to see if it exists in the second array. If it does, replace the value from the second array in the first. And at the end your first array will contain the result you want.
Like so:
$array_1 = array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2 = array("4a-walking","2a-cats");
function splitArray ($arrayInput)
{
$arrayOutput = array();
foreach ($arrayInput as $element) {
$tempArray = explode('-', $element);
$arrayOutput[$tempArray[0]] = $tempArray[1];
}
return $arrayOutput;
}
$arraySplit1 = splitArray($array_1);
$arraySplit2 = splitArray($array_2);
foreach ($arraySplit1 as $key1 => $value1) {
if (array_key_exists($key1, $arraySplit2)) {
$arraySplit1[$key1] = $arraySplit2[$key1];
}
}
print_r($arraySplit1);
See it working here:
http://3v4l.org/2BrVI
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
function merge_array($arr1, $arr2) {
$arr_tmp1 = array();
foreach($arr1 as $val) {
list($key, $val) = explode('-', $val);
$arr_tmp1[$key] = $val;
}
foreach($arr2 as $val) {
list($key, $val) = explode('-', $val);
if(array_key_exists($key, $arr_tmp1))
$arr_tmp1[$key] = $val;
}
return $arr_tmp1;
}
$result = merge_array($array_1, $array_2);
echo '<pre>';
print_r($result);
echo '</pre>';
This short code works properly, you'll get this result:
Array
(
[1a] => dogs
[2a] => cats
[3a] => birds
[4a] => walking
)
I have two array.
1st array is $newarray = ('489289', '536516', '332833', '536516')
2nd array is
$rockin = array(
'489289' => array('536516','value1'),
'332833' => array('536516'),
);
I want to delete some value of $newarray.
Suppose we are looping from $newarray
Initially 489289 is assigned value.
I want to check whether the value associated to 489289 from $rockin array (i.e. value1 or 536516) also exist in $newarray.
If there is exist 'value1' or '536516' in $newarray then, delete 489289 from array!
So in above case 489289 would be deleted (from $newarray)
AS 536516 is associated value of 489289 in $rockin array AND 536516 also exist in $newarray
Till now I have tried this code
foreach ($newarray as $group_id) {
foreach ($rockin as $myfrcikingcl) {
foreach ($myfrickingcl as $myfrickingleader) {
if($group_id==$myfrickingleader)
{
unset($newarray[$group_id]);
}
}
}
}
This is what I understood you want to do:
$newarray = array('489289', '536516', '332833', '536516');
$rockin = array(
'489289' => array('536516','332833'),
'332833' => array('536516'),
);
foreach ($rockin as $array) {
foreach ($array as $value) {
if (in_array($value, $newarray)) {
$key = array_search($array, $rockin);
$newarray = array_diff($newarray, array($key));
}
}
}
foreach ($newarray as $k => $v) {
if(is_array($rockin[$v])){
foreach ($rockin[$v] as $key => $value) {
if(in_array($value, $newarray)){
unset($newarray[$k]);
}
}
}
}
You're using $group_id as a key, but it's a value. You have to unset by key, like this:
foreach ($i = 0; $i < count($newarray); $i++) {
foreach ($rockin as $myfrcikingcl) {
foreach ($myfrickingcl as $myfrickingleader) {
if ($newarray[$i] == $myfrickingleader) {
unset($newarray[$i]);
}
}
}
}