I write a code for sync two array and know which was must delete and which was add to new array.
<?php
$currentArray = array('ali', 'hasan', 'husein'); //base array read from database
$saveArray = array('husein', 'Hasan', 'taghi'); //requested item for save/delete in database
$deleteArray = array();
$addArray = array();
$currentArray = array_map('strtolower', $currentArray);
$saveArray = array_map('strtolower', $saveArray);
foreach ($currentArray as $a) {
if (!in_array($a, $saveArray))
$deleteArray[] = $a;
}
foreach ($saveArray as $a) {
if (!in_array($a, $currentArray))
$addArray[] = $a;
}
echo 'must be deleted:';
var_dump($deleteArray);
echo 'must be added:';
var_dump($addArray);
?>
Output:
must be deleted:
array
0 => string 'ali' (length=3)
must be added:
array
0 => string 'taghi' (length=5)
Now, Do you thinks is it better, faster and simpler code for this action?
You can use array_udiff() for this, using strcasecmp() as the callback function.
$currentArray = array('ali', 'hasan', 'husein');
$saveArray = array('husein', 'Hasan', 'taghi');
$deleteArray = array_udiff($currentArray, $saveArray, 'strcasecmp');
$addArray = array_udiff($saveArray, $currentArray, 'strcasecmp');
See demo
The values must be the same.
$currentArray = array_map('strtolower', $currentArray);
$saveArray = array_map('strtolower', $saveArray);
And basically use use Array diff.
$deleteArray = array_diff($currentArray, $saveArray);
$addArray = array_diff($saveArray, $currentArray);
Related
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
)
This question already has answers here:
How does PHP 'foreach' actually work?
(7 answers)
Closed 8 years ago.
Consider the code below:
<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'] = 'apple';
}
?>
It is not displaying 'a'. How foreach works with hash-table(array), to traverse each element. If lists are implement why can't I add more at run time ?
Please don't tell me that I could do this task with numeric based index with help of counting.
Foreach copies structure of array before looping(read more), so you cannot change structure of array and wait for new elements inside loop. You could use while instead of foreach.
$arr = array();
$arr['b'] = 'book';
reset($arr);
while ($val = current($arr))
{
print "key=".key($arr).PHP_EOL;
if (!isset($arr['a']))
$arr['a'] = 'apple';
next($arr);
}
Or use ArrayIterator with foreach, because ArrayIterator is not an array.
$arr = array();
$arr['b'] = 'book';
$array_iterator = new ArrayIterator($arr);
foreach($array_iterator as $key=>$val) {
print "key=>$key\n";
if(!isset($array_iterator['a']))
$array_iterator['a'] = 'apple';
}
I think you need to store array element continue sly
Try
<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'][] = 'apple';
}
print_r($arr);
?>
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
http://cz2.php.net/manual/en/control-structures.foreach.php
Try this:
You will get values.
<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'] = 'apple';
}
echo '<pre>';
print_r($arr);
?>
Output:
key=>b
<pre>Array
(
[b] => book
[a] => apple
)
If you want to check key exist or not in array use array_key_exists function
Eg:
<?php
$arr = array();
$arr['b'] = 'book';
print_r($arr); // prints Array ( [b] => book )
if(!array_key_exists("a",$arr))
$arr['a'] = 'apple';
print_r($arr); // prints Array ( [b] => book [a] => apple )
?>
If you want to use isset condition try like this:
$arr = array();
$arr['b'] = 'book';
$flag = 0;
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr["a"]))
{
$flag = 1;
}
}
if(flag)
{
$arr['a'] = 'apple';
}
print_r($arr);
How about using for and realtime array_keys()?
<?php
$arr = array();
$arr['b'] = 'book';
for ($x=0;$x<count($arr); $x++) {
$keys = array_keys($arr);
$key = $keys[$x];
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'] = 'apple';
}
I have a web service to identify people and their functions from an external database that returns me a set of data if the login is successful. The data (that interests me right now) is separated in different strings as follow:
$groups="group1, group2, group3"
$functions="member, member, admin"
The first element of the string $groups corresponds to the first element of the $functions string.
We can have empty spots in the strings:
$groups="group1,, group3";
$functions="member,, admin";
What is the best way to combine them to obtain:
$usertype(
group1=>member,
group2=>member,
group3=>admin,
);
Then I plan to use array_search() to get the name of the group that corresponds to a function.
This is very trick especially when the first element is empty but here is a comprehensive solution
What you need is :
// Your Varriables
$groups = "group1,, group3";
$functions = "member,, admin";
// Break Into Array
$groups = explode(",", $groups);
$functions = explode(",", $functions);
// Combine both new Arrays and Output Result
$new = array_combine($groups, $functions);
print_r($new);
If you need to fix null values then :
Example :
// Your Varriables
$groups = "group1,, group3";
$functions = "member,, admin";
// Break Into Array
$groups = explode(",", $groups);
$functions = explode(",", $functions);
// Fix Null Values
$groups = fixNull($groups, true);
$functions = fixNull($functions);
// Combine both new Arrays and Output Result
$new = array_combine($groups, $functions);
print_r($new);
Output
Array
(
[group1] => member
[group2] => member
[group3] => admin
)
See Live DEMO
More Complex:
// Your Varriables
$groups = ",,, group3";
$functions = ",member,, admin";
// Fix Null Values
$groups = fixNull(explode(",", $groups), true);
$functions = fixNull(explode(",", $functions));
// Combine both new Arrays and Output Result
$new = array_combine($groups, $functions);
print_r($new);
Output
Array
(
[group4] => member
[group5] => member
[group6] => member
[group3] => admin
)
Live DEMO
Function Used
function fixNull($array, $inc = false) {
$ci = new CachingIterator(new ArrayIterator($array), CachingIterator::FULL_CACHE);
if ($inc) {
$next = array_filter($array);
$next = current($next);
$next ++;
} else {
$next = array_filter($array);
sort($next);
$next = end($next);
}
$next || $next = null;
$modified = array();
foreach($ci as $item) {
$modified[] = empty($item) ? trim($next) : trim($item);
if (! $ci->getInnerIterator()->current()) {
$item || $item = $next;
$next = $inc ? ++ $item : $item;
}
}
return $modified;
}
$groups = explode(",", $groups);
$functions = explode(",", $functions);
//then use the elements of the $groups array as key and the elements of the $functions array as the value
$merged = array_combine($groups, $functions);
Something along the lines of this should help:
$usertype = array_combine(explode(',', $groups), explode(',', $functions));
Use explode() to make arrays of your strings, and array_combine() to use one array as keys, the other one as values.
$groups = "group1, group2, group3";
$functions = "member, member, admin";
$usertype = array_combine(explode(", ", $groups), explode(", ", $functions));
Have you tried a explode($delimiter , $string) and then filter the array? I think that would be a good way of doing it:
$groups="group1,, group3";
$functions="member,, admin";
$groups_array = array_map('trim',explode(',', $groups));
$functions_array = array_map('trim',explode(',', $functions));
$final = array();
for ($i = 0; $i <= count($groups_array); $i++) {
$final[$groups_array[$i]] = $functions_array[$i];
}
$merged = array_combine($groups_array, $functions_array);
Demo
$groups="group1, group2, group3"
$functions="member, member, admin"
preg_match_all('/\w+/', $groups, $groups);
preg_match_all('/\d+/', $functions, $functions);
$final = array();
foreach ($groups[0] AS $key => $letter)
$final[] = $letter . '=>' . $functions[0][$key];
echo join(', ', $final);
explode and array_combine.
Note that you have a problem with whitespaces. Therefore use the following:
<?php
$groups="group1, group2, group3";
$functions="member, member, admin";
$groupArray = array_map(function($element){return trim($element);},
explode(',',$groups)); // split into array and remove leading and ending whitespaces
$functionArray = array_map(function($element){return trim($element);},
explode(',',$functions)); // split into array and remove leading and ending whitespaces
print_r(array_combine($groupArray,$functionArray));
?>
This will output:
Array
(
[group1] => member
[group2] => member
[group3] => admin
)
EDIT: removed trim for the possibility that the first element is empty.
I have several arrays: $n, $p, $a
Each array is the same:
$n = array()
$n['minutes'] = a;
$n['dollars'] = b;
$n['units'] = c;
$p = array()
$p['minutes'] = x;
$p['dollars'] = y;
$p['units'] = z;
etc...
I also have a simple array like this:
$status = array('n', 'p', 'a');
Is it possible for me to use the $status array to loop through the other arrays?
Something like:
foreach($status as $key => $value) {
//display the amounts amount here
};
So I would end up with:
a
x
b
y
c
z
Or, do I need to somehow merge all the arrays into one?
Use:
$arrayData=array('minutes','dollars','units');
foreach($arrayData as $data) {
foreach($status as $value) {
var_dump(${$value}[$data]);
}
}
foreach($n as $key => $value) {
foreach($status as $arrayVarName) (
echo $$arrayVarName[$key],PHP_EOL;
}
echo PHP_EOL;
}
Will work as long as all the arrays defined in $status exist, and you have matching keys in $n, $p and $a
Updated to allow for $status
You could use next() in a while loop.
Example: http://ideone.com/NTIuJ
EDIT:
Unlike other answers this method works whether the keys match or not, even is the arrays are lists, not dictionaries.
If I understand your goal correctly, I'd start by putting each array p/n/... in an array:
$status = array();
$status['n'] = array();
$status['n']['minutes'] = a;
$status['n']['dollars'] = b;
$status['n']['units'] = c;
$status['p'] = array();
$status['p']['minutes'] = a;
$status['p']['dollars'] = b;
$status['p']['units'] = c;
Then you can read each array with:
foreach($status as $name => $values){
echo 'Array '.$name.': <br />';
echo 'Minutes: '.$values['minutes'].'<br />';
echo 'Dollars: '.$values['dollars'].'<br />';
echo 'Units: '.$values['units'].'<br />';
}
For more information, try googling Multidimensional Arrays.
I need to create array like that:
Array('firstkey' => Array('secondkey' => Array('nkey' => ...)))
From this:
firstkey.secondkey.nkey.(...)
$yourString = 'firstkey.secondkey.nkey';
// split the string into pieces
$pieces = explode('.', $yourString);
$result = array();
// $current is a reference to the array in which new elements should be added
$current = &$result;
foreach($pieces as $key){
// add an empty array to the current array
$current[ $key ] = array();
// descend into the new array
$current = &$current[ $key ];
}
//$result contains the array you want
My take on this:
<?php
$theString = "var1.var2.var3.var4";
$theArray = explode(".", $theString); // explode the string into an array, split by "."
$result = array();
$current = &$result; // $current is a reference to the array we want to put a new key into, shifting further up the tree every time we add an array.
while ($key = array_shift($theArray)){ // array_shift() removes the first element of the array, and assigns it to $key. The loop will stop as soon as there are no more items in $theArray.
$current[$key] = array(); // add the new key => value pair
$current = &$current[$key]; // set the reference point to the newly created array.
}
var_dump($result);
?>
With an array_push() in the while loop.
What do you want the value of the deepest key to be?
Try something like:
function dotToArray() {
$result = array();
$keys = explode(".", $str);
while (count($keys) > 0) {
$current = array_pop($keys);
$result = array($current=>$result);
}
return $result;
}