How To Get The Original Key From Sliced Array? - php

I have this code :
<?php
$order_list = array ( array ("tangible", 1, 8, 33, 19000),
array ("tangible", 1, 9, 8, 19000),
array ("tangible", 1, 3, 24, 19000),
array ("tangible", 1, 2, 10, NULL),
array ("tangible", 1, 17, 11, 28000));
$num = 2;
foreach(array_slice($order_list, $num) as $key => $value) {
echo $key.'=>'.$value[2].'<br>';
}
?>
and the result is this :
0=>3
1=>2
2=>17
the problem is... $value = 3 has $key = 0, while in the $order_list this value has $key = 2.
so, I'm expecting $key from $order_list based on value sliced. how to do that?
thank you.

....and the manual says: http://us3.php.net/manual/en/function.array-slice.php
The fourth argument, preserve_keys.

Related

Creating a list and indexing

Given a two list. Create a third list by picking an odd-index element from the first list and even index elements from the second.
For Example:
listOne = [3, 6, 9, 12, 15, 18, 21]
listTwo = [4, 8, 12, 16, 20, 24, 28]
Expected Output:
Printing Final third list
[6, 12, 18, 4, 12, 20, 28]
I think, it will be helpful for you.
<?php
$listOne = [3, 6, 9, 12, 15, 18, 21];
$listTwo = [4, 8, 12, 16, 20, 24, 28];
$NlistOne=[];
$NlistTwo=[];
//odd-index positions from list one [6, 12, 18]
foreach ($listOne as $key => $value) {
if($key%2==1){
array_push($NlistOne, $value);
}
}
//even-index positions from list two [4, 12, 20, 28]
foreach ($listTwo as $key => $value) {
if($key%2==0){
array_push($NlistTwo, $value);
}
}
//Printing Final third list [6, 12, 18, 4, 12, 20, 28]
print_r(array_merge($NlistOne,$NlistTwo));
?>
Output will be:
Array ( [0] => 6 [1] => 12 [2] => 18 [3] => 4 [4] => 12 [5] => 20 [6] => 28 )
//init result array
//loop over listOne, using for($i=1;$i<sizeof($listOne);$i=$i+2)
//and add to result for each iteration, $resultArr[] = $listOne[$i]
//do the same with listTwo, but for($i=*0*
You can merge both of arrays and then pick all odd elements
$listOne = [3, 6, 9, 12, 15, 18, 21];
$listTwo = [4, 8, 12, 16, 20, 24, 28];
$result = [];
foreach ( array_merge($listOne, $listTwo) as $value ){
if ( $key % 2 ) {
$result[] = $value;
}
}
If array length isn't fixed, say it could contain not 7 elements, then you need to check it before merging to make it have odd number of elements
$listOne = [3, 6, 9, 12, 15, 18, 21, 777];
$listTwo = [4, 8, 12, 16, 20, 24, 28];
$result = [];
if ( count($listOne) % 2 !== 1 ) {
$listOne[] = 0;
}
foreach( array_merge($listOne, $listTwo) as $value ){
if ( $key % 2 ) {
$result[] = $value;
}
}
you don't have to loop over whole array array_filter will do this for you, Constant ARRAY_FILTER_USE_KEY will check each key for odd or for even
<?php
$a1 = [3, 6, 9, 12, 15, 18, 21];
$a2 = [4, 8, 12, 16, 20, 24, 28];
function odd($var)
{
// returns whether the input integer is odd
return $var & 1;
}
function even($var)
{
// returns whether the input integer is even
return !($var & 1);
}
$result= (array_merge(array_filter($a1, 'odd', ARRAY_FILTER_USE_KEY),array_filter($a2, 'even', ARRAY_FILTER_USE_KEY)));
output you will get
Array (
[0] => 6
[1] => 12
[2] => 18
[3] => 4
[4] => 12
[5] => 20
[6] => 28 )
Iterate over first one and take only values of odds indices, and loop again through second one and take evens indices.
$listOne = [3, 6, 9, 12, 15, 18, 21];
$listTwo = [4, 8, 12, 16, 20, 24, 28];
$res = [];
for ($i=0; $i < count($listOne); $i++) {
if($i & 1) // $i is odd.
$res[] = $listOne[$i];
}
for ($j=0; $j < count($listTwo); $j++) {
if(n % 2 === 0) // $j is even.
$res[] = $listTwo[$j];
}
Result:
echo "List One :".json_encode($listOne)."<br>";
echo "List Two :".json_encode($listTwo)."<br>";
echo "Lists Merged:".json_encode($res);
Output:*
/*
List One :[3,6,9,12,15,18,21]
List Two :[4,8,12,16,20,24,28]
Lists Merged:[6,12,18,4,12,20,28]
*/
Iterate over arrays:
take odds in array starting with index One and increment it by two.
take evens in array by starting with index Zero and increment it by two.
$listOne = [3, 6, 9, 12, 15, 18, 21]; $listTwo = [4, 8, 12, 16, 20, 24, 28];
$res = [];
for ($i=1; $i < count($listOne); $i+=2) {
$res[] = $listOne[$i];
}
for ($j=0; $j < count($listTwo); $j+=2) {
$res[] = $listTwo[$j];
}
print(json_encode($res)); // [6,12,18,4,12,20,28]

Sort an array of numbers by another predefined, non-exhaustive array of number, then sort ascending

Given two arrays $A1 and $A2, sort $A1 in such a way that the relative order among the elements will be same as those in $A2. For the elements not present in $A2, move them to the back of the array in ascending order.
$A1 = [2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8];
$A2 = [2, 1, 8, 3];
Desired output:
[2, 2, 1, 1, 8, 8, 3, 5, 6, 7, 9]
Coding attempt:
$sorted = array();
foreach($a1 as $key => $value) {
if(in_array($value, $a2)) {
$sorted[array_search($value, $a1)] = $value;
}
}
This can be done via for each loop :
$arr1 = array(2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8); // array to be sorted
$arr2 = array(2, 1, 8, 3); // refrence array for sort logic
// Output: A1[] = {2, 2, 1, 1, 8, 8, 3, 5, 6, 7, 9}
$sortarr = array(); // array to store final sorted values
foreach ($arr2 as $a) {
foreach ($arr1 as $k => $b) {
if($b==$a) {
$sortarr[]=$b;
unset($arr1[$k]);
}
}
}
$finalarr = array_merge($sortarr, $arr1);
print_r($finalarr);
You can use usort like this:
$k = array_flip($a2); // Create an associative array for the second array
usort($a1, function($a, $b) use ($k) {
return isset($k[$a]) ? (isset($k[$b]) ? $k[$a]-$k[$b] : -1) : (isset($k[$b]) ? 1 : $a-$b);
});
Other solutions that use a nested loop result in a time complexity of O(n²), while this has a time complexity of O(nlogn).
i tried this code and works:
<?php
/*
Input: A1[] = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8}
A2[] = {2, 1, 8, 3}
Output: A1[] = {2, 2, 1, 1, 8, 8, 3, 5, 6, 7, 9}
*/
$a1=array(2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8);
$a2=array(2, 1, 8, 3);
$a3=array();
sort($a1);//order array
//order array a3 with a2 value....
for($i=0;$i<sizeof($a2);$i++){
for($j=0;$j<sizeof($a1);$j++){
if($a1[$j]==$a2[$i]){
array_push($a3,$a2[$i]);
//if exsist value i change value in a1 in x
$a1[$j]="x";
}
}
}
//write in a3 the next number not present in a2
for($i=0;$i<sizeof($a1);$i++){
if($a1[$i]<>"x"){
array_push($a3, $a1[$i]);
}
}
print_r($a3);
//out:Array ( [0] => 2 [1] => 2 [2] => 1 [3] => 1 [4] => 8 [5] => 8 [6] => 3 [7] => 5 [8] => 6 [9] => 7 [10] => 9 )
?>
Hope this helps
I do not endorse the use of nested loops because they will be doing too many unnecessary cycles. #trincot's approach moreso represents what I would use in a professional application, but I will demonstrate a more modern and concise style with no iterated function calls.
Code: (Demo)
$arr1 = [2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8];
$arr2 = [2, 1, 8, 3];
$priority = array_flip($arr2);
$fallback = count($arr2);
usort(
$arr1,
fn($a, $b) =>
[$priority[$a] ?? $fallback, $a]
<=>
[$priority[$b] ?? $fallback, $b]
);
var_export($arr1);
// [2, 2, 1, 1, 8, 8, 3, 5, 6, 7, 9]
$arr2 is flipped into a lookup array, and count() is used when a value is not found in the lookup array. Whenever the first rule results in a tie, the second rule orders the numbers numerically in an ascending direction.
The meaning of custom function's syntax is:
[left value rule1, left value rule2] compared to [right value rule1, right value rule2]
The spaceship operator (<=>) will compare the corresponding element one at a time "rule1 vs rule1" then "rule2 vs rule2" as needed.

For-each loop, larger than 20 into another array

I'm stuck on this exercise that I can't seem to get for the life of me.
$numbers2 = [21, 5, 4, 6, 76, 2, 18, 85, 55, 1];
foreach ($numbers2 as &$value) {
$largeNumbers[] = $value > 20;
}
That's the code I have so far. What I am trying to do here is use a for-each loop to add all the numbers that are larger than 20 into another Array, which I have named $largeNumbers. The code I have inserted above seems to be printing out true and false values, which is not what I was going for. I'd really appreciate it someone could tell me what I'm possibly doing wrong or even show me a better way. I have to use a for-each loop.
For each item, you are checking if it's larger than 20, which results in a boolean value (it either is or is not), and you then store this value to the result array. Instead, you could use an if statement` to only take the elements that answer the condition:
foreach ($numbers2 as &$value) {
if ($value > 20) {
$largeNumbers[] = $value;
}
}
<?php
$nums = [21, 5, 4, 6, 76, 2, 18, 85, 55, 1];
$less_than_or_equal_to_20 = [];
foreach($nums as $v)
if($v <= 20)
$less_than_or_equal_to_20[] = $v;
$out = array_diff($nums, $less_than_or_equal_to_20);
var_export($out);
Output:
array ( 0 => 21, 4 => 76, 7 => 85, 8 => 55, )
<?php
$nums = [21, 5, 4, 6, 76, 2, 18, 85, 55, 1];
foreach([$nums] as $v)
$out = array_filter($v, function($v) {
return $v > 20;
});
var_export($out);
Output:
array ( 0 => 21, 4 => 76, 7 => 85, 8 => 55, )

How To Perform array_search In Multi Dimensional Array?

I have this code :
$order_list = array ( array ("tangible", 1, 8, 33, 19000),
array ("tangible", 1, 9, 8, 19000),
array ("tangible", 6, 3, 24, 19000),
array ("tangible", 6, 2, 10, NULL),
array ("tangible", 1, 17, 11, 28000));
$key = array_search(3, array_column($order_list, $order_list[2]));
and I want to get the value of $order_list[$i][3] based on $order_list[$i][2].
for example, if I put :
3 I will get 24 in return
9 I will get 8 in return
and so on...
I tried to use array_search :
$key = array_search(3, array_column($order_list, $order_list[2]));
but I got this error :
Warning: array_column(): The column key should be either a string or an integer in /home/***/public_html/***.php on line 8
Warning: array_search() expects parameter 2 to be array, boolean given in /home/***/public_html/***.php on line 8
how to perform array_serach in this case? thanks before.
I created a general purpose function to get next value of current value in 2'd array. have a look on below function. Also look at variable description of function to understand input in function:
/***
* #param array $array input array
* #param $search_value value that need to be searched
* #param $search_index index of inner array where current value exists
* #return next value of current value
*/
function getNextSequence(array $array, $search_value, $search_index)
{
$result = null;
$key = array_search($search_value, array_column($array, $search_index));
if ($key !== false) {
$result = (isset($array[$key][$search_index + 1])) ? $array[$key][$search_index + 1] : null;
}
return $result;
}
$order_list = array(
array("tangible", 1, 8, 33, 19000),
array("tangible", 1, 9, 8, 19000),
array("tangible", 6, 3, 24, 19000),
array("tangible", 6, 2, 10, NULL),
array("tangible", 1, 17, 11, 28000)
);
var_dump(getNextSequence($order_list, 3, 2)); //output: int(24)
var_dump(getNextSequence($order_list, 9, 2)); //output: int(8)
var_dump(getNextSequence($order_list, 10, 2)); //output: Null
var_dump(getNextSequence($order_list, 2, 2)); //output: int(10)
<?php
$search = 9;
$order_list = array ( array ("tangible", 1, 8, 33, 19000),
array ("tangible", 1, 9, 8, 19000),
array ("tangible", 6, 3, 24, 19000),
array ("tangible", 6, 2, 10, NULL),
array ("tangible", 1, 17, 11, 28000));
foreach ($order_list as $string){
if (in_array($search,$string)){
//repsonse here
}
}
?>
another way.....
$search = 9;
$order_list = array ( array ("tangible", 1, 8, 33, 19000),
array ("tangible", 1, 9, 8, 19000),
array ("tangible", 6, 3, 24, 19000),
array ("tangible", 6, 2, 10, NULL),
array ("tangible", 1, 17, 11, 28000));
foreach ($order_list as $string){
if ($string[2] == $search){
print_r( $string);
}
}

is it possible to array push value into existing array value with sum?

is it possible to array push value into existing array value with sum?
$nvArr = Array("1"=> 35, "2"=> 1, "3"=> 2, "8"=> 56, "9"=> 78);
I have add one more array value into existing array
$nvArr1 = Array("1"=> 35, "2"=> 1);
And i want to like following out put
$nvArr = Array("1"=> 70, "2"=> 2, "3"=> 2, "8"=> 56, "9"=> 78);
you can do it with foreach
foreach($nvArr1 as $key => $val){
(array_key_exists($key, $invArr))?
$invArr[$key] += $nvArr1[$key]
: $invArr[$key] = $nvArr1[$key]
}

Categories