PHP renumber array but keep sequence - php

I have an array like this:
array(13,4,7,1,16);
I want to recount the array, but I want to keep the sequence, like this:
array(4,2,3,1,5);
How can I do this?

If you are trying to sort the array, keeping the keys in the same order as the values, the PHP asort() function does that.
If you want to keep the original array but get the keys in sort order, then you can use something like:
$arr = array(13,4,7,1,16);
asort($arr);
$keys = array_keys($arr);
Then $keys has the keys from the original array sorted in the order of the original values, e.g. $keys = array(4,2,3,1,5);

if you want to get the index of the array with reference to the sorted values
Try this
$numbers = array(13,4,7,1,16);
$numberscopy = $numbers;
sort($numberscopy);
$final = array();
//echo array_search(13, $numbers);
for($a=0 ; $a<count($numberscopy );$a++){
$final[] = array_search($numberscopy[$a], $numbers) + 1;
}
var_dump($final);

Related

PHP removing a specific array from a multidimensional array

I have a multidimensional array in PHP where I need to remove one array based on the value of an item in one of the arrays:
Example Array
array(
"0"=>array("0"=>"joe", "1"=>"2018-07-18 09:00:00"),
"1"=>array("0"=>"tom", "1"=>"2018-07-17 09:00:00"),
"2"=>array("0"=>"joe", "1"=>"2018-07-14 09:00:00")
)
I know that I want to remove the array that contains joe in key 0, but I only want to remove the array that contains joe with the most current date in key1. The following output is what I'm trying to accomplish:
array(
"0"=>array("0"=>"tom", "1"=>"2018-07-17 09:00:00"),
"1"=>array("0"=>"joe", "1"=>"2018-07-14 09:00:00")
)
Is there a simple way to do this in PHP aside from looping through each array?
Here is a non looping method that uses array_intersect and array_column to find the "Joe's" and then deletes the maximum array_key since I first sort the array on dates.
usort($arr, function($a, $b) {
return $a[1] <=> $b[1];
}); // This returns the array sorted by date
// Array_column grabs all the names in the array to a single array.
// Array_intersect matches it to the name "Joe" and returns the names and keys of "Joe"
$joes = array_intersect(array_column($arr, 0), ["joe"]);
// Array_keys grabs the keys from the array as values
// Max finds the maximum value (key)
$current = max(array_keys($joes));
unset($arr[$current]);
var_dump($arr);
https://3v4l.org/mah6K
Edit forgot to add the array_values() if you want to reset the keys in the array.
Just add $arr = array_values($arr); after the unset.
I would go about it like this:
<?php
$foo = array(
"0"=>array("0"=>"joe", "1"=>"2018-07-18 09:00:00"),
"1"=>array("0"=>"tom", "1"=>"2018-07-17 09:00:00"),
"2"=>array("0"=>"joe", "1"=>"2018-07-14 09:00:00")
);
$tmp = [];
foreach($foo as $k => $v) {
if ($v[0] === 'joe') {
$tmp[$v[1]] = $k;
}
}
if (!empty($tmp)) {
sort($tmp); //think that is sane with date format?
unset($foo[reset($tmp)]);
}
var_dump($foo);
Not sure if you don't want to loop on principal or what... I tend to go for readability. Find all occurrences of joe. Sort on date. Remove the most recent by key.

How to change key array php

How to change key array php from
array(
[0]=>Joni
[1]=>Jono
[2]=>Riki
[3]=>Budi
);
Change index to:
array(
[nominal]=>Joni
[nominal]=>Jono
[nominal]=>Riki
[nominal]=>Budi
);
you can make a multi-dimensional array for this purpose
$arr = array('a','b','c','d');
for($i=0;$i<count($arr);$i++){
$newArr['nominal'][$i] = $arr[$i];
}
print_r($newArr);
The expected outcome you want is not possible at all, because same indexes will be over-written in single-dimensional array.
Check this to understand what i said above:- https://eval.in/954556
Now there are 2 closer possiblities of outcomes, which i am going to mention:-
$possibility1 = [];
$possibility2 =[];
foreach($array as $arr){
$possibility1[] = ['nominal'=>$arr];
$possibility2['nominal'][] = $arr;
}
print_r($possibility1);//first closer possibility
print_r($possibility2);//second closer possibility
Output:- https://eval.in/954559

How to export each subarrays as an array in PHP

is it possible that, get arrays to $value with key:
Example:
$array = Array("one"=>Array("field1"=>"value1","field2"=>"value2"),
"two"=>Array("field3"=>"value3","field4"=>"value4"));
Export arrays to value:
$first = any_main_php_function_name(0,$array);
$second = any_main_php_function_name(1,$array);
Result:
$first = Array("field1"=>"value1","field2"=>"value2");
$second = Array("field3"=>"value3","field4"=>"value4");
Basically, I wanna extract multiple array. If there is no such function (any_main_php_function_name) in PHP so How can i extract above $array.
You don't need any funtion to do that. Simply get subarrays like this:
$first = $array['one'];
$second = $array['two'];
Unless you don't know the one,two keys, then you can use array_shift to get first item (one subarray). Remember that this functions also removes returned value from root array.
array_slice does what you want
$first = array_slice($array, 0, 1);
$second = array_slice($array, 1, 1);
print_r($first);
print_r($second);
May be you can array_shift to get the element from array, Like this:
$first_element=array_shift($array);
Make sure it only removes the first element from the array and
return the value of removed element.
And if you don't want to remove the element or get the sub-array in any sequence, then you can create a function like this,
function myFunction($index,$array) {
$keys = array_keys($array);
$sub_array=$arr[$keys[$index]];
}
In above function we just get the keys in a array and then use the known index to get the sub-array using keys array.
Please check this
foreach($array["one"] as $key=>$val){
echo "key=>".$key." Values=>".$val;
}
foreach($array["true"] as $key=>$val){
echo "key=>".$key." Values=>".$val;
}

Sort array by value and store in variable

$array = array(5,4,6,8,5,3,4,6,1);
I want to sort $array like asort does, but the problem is that asort is a function and its product can't be stored in a variable.
How can I do something like this?:
$array = array(5,4,6,8,5,3,4,6,1);
$sorted_array = asort($array);
Edit: I also want $array to keep its original order.
Do this for maintaining $array in its original order
$array = array(5,4,6,8,5,3,4,6,1);
$sorted_array = $array;
asort($sorted_array);
Output
http://codepad.viper-7.com/8E78Fo
$orignal_array = array(5,4,6,8,5,3,4,6,1);
$copied_array = $orignal_array;
asort($copied_array);
$sorted_array = $copied_array;
not the most efficient way to do it though :(
Sort it first and then assign it
asort($array);
$sorted_array = $array

Interleaving multiple arrays into a single array

I need to merge several arrays into a single array. The best way to describe what I'm looking for is "interleaving" the arrays into a single array.
For example take item one from array #1 and append to the final array. Get item one from array #2 and append to the final array. Get item two from array #1 and append...etc.
The final array would look something like this:
array#1.element#1
array#2.element#1
.
.
.
The "kicker" is that the individual arrays can be of various lengths.
Is there a better data structure to use?
for example,
function array_zip_merge() {
$output = array();
// The loop incrementer takes each array out of the loop as it gets emptied by array_shift().
for ($args = func_get_args(); count($args); $args = array_filter($args)) {
// &$arg allows array_shift() to change the original.
foreach ($args as &$arg) {
$output[] = array_shift($arg);
}
}
return $output;
}
// test
$a = range(1, 10);
$b = range('a', 'f');
$c = range('A', 'B');
echo implode('', array_zip_merge($a, $b, $c)); // prints 1aA2bB3c4d5e6f78910
If the arrays only have numeric keys, here's a simple solution:
$longest = max( count($arr1), count($arr2) );
$final = array();
for ( $i = 0; $i < $longest; $i++ )
{
if ( isset( $arr1[$i] ) )
$final[] = $arr1[$i];
if ( isset( $arr2[$i] ) )
$final[] = $arr2[$i];
}
If you have named keys you can use the array_keys function for each array and loop over the array of keys instead.
If you want more than two arrays (or variable number of arrays) then you might be able to use a nested loop (though I think you'd need to have $arr[0] and $arr[1] as the individual arrays).
I would just use array_merge(), but that obviously depends on what exactly you do.
This would append those arrays to each other, while elements would only be replaced when they have the same non-numerical key. And that might not be a problem for you, or it might be possible to be solved because of attribute order, since the contents of the first arrays' elements will be overwritten by the later ones.
If you have n arrays, you could use a SortedList, and use arrayIndex * n + arrayNumber as a sort index.

Categories