From the 2nd element in $array, increment the key by 100, suppose the keys are all numeric.
You can do:
$keys = array_keys($array); // extract keys.
$values = array_values($array); // extract values.
for($i=1;$i<count($keys);$i++) { // increment keys start 2nd key.
$keys[$i] += 100;
}
$array = array_combine($keys,$values); // combine back
$new_array = array();
$count = 0;
foreach ($original_array as $key => $value)
{
if ($count > 0)
$new_array[$key + 100] = $value;
else
$new_array[$key] = $value;
$count++;
}
Now $new_array contains your "shifted" $original_array, starting from element #2.
As noted in comments below, the following solution will only work well for moving a single element.
reset($array); //moves pointer to the beginning
next($array); //moves pointer to 2nd element
$array[key($array)+100] = current($array); // copies current element to incremented key
unset($array[key($array)]); //remove the element
Related
I have 2 SELECT statement in my PHP. Both the select statements fetch data from two different DB. The fetched data is saved in PDO Assoc Array. The problem is when I want to compare those two arrays to find that if the column 'id' exist in both arrays or not. If it exists then ignore it. If it's a unique id then save it into a third array. But I found some problems in my Logic Below
And after running the below code I am getting a couple of error:
1: Array to string conversion
2: duplicate key value violates unique constraint
$arr1 = $msql->fetchAll(PDO::FETCH_ASSOC);
$array1 = array();
foreach($arr1 as $x){
$array1[] = $x['id'];
}
$arr2 = $psql->fetechAll(PDO::FETCH_ASSOC);
$array2 = array();
foreach($arr2 as $y){
$array2[] = $y['id'];
}
$finalarray = array();
for ($i = 0; $i < count($arr1); $i++){
if(count(array_intersect($array1,$array2)) <= 1){// is the count of id is 1 or less save that whole row in the $finalarray
$finalarray = $arr1[$i]; // saving the unique row.
}
else{
continue;
}
}
All I am trying to get the unique row of data array() after comparing their id column.
You can use in_array() function as both arrays are index array.
$finalarray = array();
for ($i = 0; $i < count($arr1); $i++){
if(count(array_intersect($array1,$array2)) <= 1){// is the count of id is 1 or less save that whole row in the $finalarray
$finalarray = $arr1[$i]; // saving the unique row.
}
else{
continue;
}
}
make change in code:
$finalarray = array();
for ($i = 0; $i < count($arr1); $i++){
if(!in_array($array1[$i], $array2)){
$finalarray[] = $array1[$i]; // saving the unique row.
}
}
You can simply use array_intersect() to get common values between two array. for difference, can use array_diff()
$array1 = [1,2,3,4,5,6,7];
$array2 = [2,4,6];
//array_intersect — Computes the intersection of arrays
$result = array_intersect($array1, $array2);
print_r($result);
//array_diff — Computes the difference of arrays
$result = array_diff($array1, $array2);
print_r($result);
DEMO
Rather than using 3 different arrays to get unique ids, you can do it by using one array. Make changes to your code as below:
$finalarray = array();
$arr1 = $msql->fetchAll(PDO::FETCH_ASSOC);
foreach($arr1 as $x){
if (!in_array($x['id'],$finalarray)) { // check id is already stored or not
$finalarray[] = $x['id'];
}
}
$arr2 = $psql->fetechAll(PDO::FETCH_ASSOC);
foreach($arr2 as $y){
if (!in_array($y['id'],$finalarray)) { // check id is already stored or not
$finalarray[] = $y['id'];
}
}
Maybe you should make sure which array is larger before your loop ;
Or using array_diff:
$finalarray = array_diff($array1 , $array2) ?? [];
$finalarray = array_merge( array_diff($array2 , $array1) ?? [], $finalarray );
I have an associative array, $teams_name_points. The length of the array is unknown.
How do I access the first and forth value without knowing the key of this array in the easiest way?
The array is filled like this:
$name1 = "some_name1";
$name2 = "some_name2";
$teams_name_points[$name1] = 1;
$teams_name_points[$name2] = 2;
etc.
I want to do something like I do with an indexed array:
for($x=0; $x<count($teams_name_points); $x++){
echo $teams_name_points[$x];
}
How do I do this?
use array_keys?
$keys = array_keys($your_array);
echo $your_array[$keys[0]]; // 1st key
echo $your_array[$keys[3]]; // 4th key
You can use array_values which will give you a numerically indexed array.
$val = array_values($arr);
$first = $val[0];
$fourth = $val[3]
In addition to the array_values, to loop through as you show:
foreach($teams_name_points as $key => $value) {
echo "$key = $value";
}
You can get use the array_keys function such as
//Get all array keys in array
$keys = array_keys($teams_name_points);
//Now get the value for 4th key
//4 = (4-1) --> 3
$value = $teams_name_points[$keys[3]];
You can get all values now as exists
$cnt = count($keys);
if($cnt>0)
{
for($i=0;$i<$cnt;$i++)
{
//Get the value
$value = $team_name_points[$keys[$i]];
}
}
I need to remove all elements in the array that comes after the FIRST instance of an element that matches same string value before the dot. ie, not taking into consideration any values after the .
from
$array = ("ItemNew1.1", "Item2.0", "Item3Test.0", "Item2.2", "Item4.4", "Item2.5")
to
$array = ("ItemNew1.1", "Item2.0", "Item3Test.0", "Item4.4")
The code below creates a temp array to hold the values that are already in the array, it runs a foreach on the original array and if the value is not in the temporary array, it inserts it into a new array
$tempArray = array();
$newArray = array();
foreach($array as $value) {
list($item, ) = explode(".", $value);
$int = filter_var($item, FILTER_SANITIZE_NUMBER_INT);
if(!in_array($int, $tempArray)) {
$newArray[] = $value;
$tempArray[] = $int;
}
}
Now, $newArray is the array that you want.
DEMO
I have a multidimensional array in PHP taking on the form of the following:
$data = array(
array('spot'=>1,'name'=>'item_1'),
array('spot'=>2,'name'=>'item_2'),
array('spot'=>1,'name'=>'item_3'),
);
If more than one array element contains a duplicate for the 'spot' number I would want to randomly select a single one and unset all other elements with the same 'spot' value. What would be the most efficient way to execute this? The resulting array would look like:
$data = array(
array('spot'=>2,'name'=>'item_2'),
array('spot'=>1,'name'=>'item_3'),
);
Store the values of spot in another array. Using array_count_values check which values occur more than once. Find the keys for those values. Select a random key. Delete all keys except the selected key from the original array. Here is the code:
$data = array(
array('spot'=>1,'name'=>'item_1'),
array('spot'=>2,'name'=>'item_2'),
array('spot'=>1,'name'=>'item_3'),
);
$arr = array();
foreach($data as $val){
$arr[] = $val['spot'];
}
foreach(array_count_values($arr) as $x => $y){
if($y == 1) continue;
$keys = array_keys($arr, $x);
$rand = $keys[array_rand($keys)];
foreach($keys as $key){
if($key == $rand) continue;
unset($data[$key]);
}
}
So I have a variable which I explode:
$values = explode ('|', $split);
This can contain any number of values from 1 to 10+
I have another big array let's call it $tree. I need to loop round the $values whilst building up an array based on the $tree variable.
E.g:
$newArray = $tree [$values [0]][$values [1]];
But this needs to be done dynamically based on the number of elements in the $values array.
Any ideas?
Thanks
Is this what you're trying to do?
$newArray = array();
foreach($values as $key => $val)
{
$newArray[] = $tree[$val][$values[$key + 1]];
}
You need a foreach loop that goes to every single value you have and then put them in the $tree array something like:
$newArray = array();
foreach($values as $index => $value)
{
$newArray[] = $tree[$value][$value[$index + 1]];
}
create a temporary array from $tree and iterate through the values getting each index:
$result = $tree;
foreach ($values as $val){
$result = $result[$val];
}
This way you go down one level deeper into $tree with each value supplied in $values, and $result holds the value stored in $tree at the point you have reached. For example if you have a navigation tree, $values would be the "breadcrumb" of the current navigation position, and $result is the remaining tree from this point downwards.
I think this is what you want. It goes through pairs of elements of $values, using them as the indexes into $tree to add to $newArray
$newArray = array();
for ($i = 0; $i < count(values); $i += 2) {
$newArray[] = $tree[$values[$i]][$values[$i+1]];
}
$values=array(0, 1, 3);
$tree=array("First", "Second", "Third", "Fourth");
$newarray=array();
for ($i=0; $i<count($values); $i++)
{
$newarray[]=$tree[$values[$i]];
}
echo(implode($newarray,", "));
Something like that what you were looking for?