Dividing array by comparing flag using array functions in php [duplicate] - php

This question already has answers here:
Split associative array by key
(6 answers)
Get the first N elements of an array?
(5 answers)
php - get numeric index of associative array
(7 answers)
Closed 2 years ago.
There is an array in php
$sampleArray = array('first' => 'first', 'second' => 'second', 'third' => 'third');
I need to splitting the array based on value $check, if the $check is 'second', then the array need to be split like this
$requiredArray = array('third'=>'third')
$nonReqArray = array('first'=>'first','second'=>'second')
if the $check is 'third' then the $requiredArray will be empty. Please suggest the solution to this?
Tried with this
$afterResult = array_filter($sampleArray, function($key) use (&$requiredArray, &$nonReqArray, &$check) {
if($key > $check){
$requiredArray[$key] = $key;
}else{
$nonReqArray[$key] = $key;
}
return true;
},
ARRAY_FILTER_USE_KEY);

Usually solved with for loops. But we can solve by array_filter array function. The main issue is indexing is not numerical, so comparing is not easy.
$cmp = false;
$afterResult = array_filter($sampleArray, function($key) use (&$requiredArray, &$nonReqArray, &$check, &$cmp) {
if($cmp){
$requiredArray[$key] = $key;
}else{
$nonReqArray[$key] = $key;
}
if($key == $check){
$cmp =true;
}
return true;
},
ARRAY_FILTER_USE_KEY);
This worked for me.

Related

How to allow same keys in one array? [duplicate]

This question already has answers here:
PHP Associative Array Duplicate Keys
(6 answers)
Closed 4 years ago.
I need to add the same keys to the array, but with different values,
foreach ($selections as $selection) {
$array += [$selection['option_id']=>$selection['product_id']];
}
// example output
$array = [30=>12,14=>10],
but really it should be
[30=>7,30=>12,14=>10];
When the key repeats, it merges.
You just can't.
But you can make the value of this key an array.
So you'll have
$array = [30=>[7,12],14=>10];
You can use any array functions on $array[30]
What you should do is to return the products ids as an array:
$array = array_reduce($selections, function ($carry, $selection) {
if (!isset($carry[$selection['option_id']])) {
$carry[$selection['option_id']] = [];
}
$carry[$selection['option_id']][] = $selection['product_id'];
return $carry;
}, []);
Now the result would be:
[30 => [7, 12], 14 => [10]];
Keys in array are, as the word itself says, keys to access the value they contain and each key must be unique, else you won't have a way to . If you could have two time or more the same value, how could you tell which will access one value and which one will access the other one? To solve your problem you have a way: generate a multidimensional array such that you can have multiple value stored "behind" a single key. E.g. [30 => [7,12], 14 => 10]
Based on your code you can just create a double loop with a nested foreach to navigate through all the value, something like:
foreach ($selections as $selection) {
if(!is_array($selection['product_id']) $array += [$selection['option_id']=>$selection['product_id']];
else {
foreach ($selection['product_id'] as $product) {
$array += [$selection['option_id']=> product];
}
}
}

Search for value in array of associative arrays using php [duplicate]

This question already has answers here:
Search in array, like select?
(3 answers)
Closed 4 years ago.
How to find the array which contains moo == 'gyu'?
$arr = [
['moo' => 'abc', 'foo' => 1], ['moo' => 'gyu', 'foo' => 2] ...
]
I know that should be answered already but unfortunately I wasn't able to find an example.
Thank you.
Use array_filter() to to find target array. In callback function check value of moo index.
$newArr = array_filter($arr, function($item){
return $item['moo'] == 'gyu';
});
Also you can use array_reduce() that return target array in result.
$newArr = array_reduce($arr, function($carry, $item){
$item['moo'] == 'gyu' ? $carry = $item : "";
return $carry;
});
Check result in demo
You have to used array_search() function for that.
if(array_search('gyu', array_column($arr, 'moo')) !== False) {
echo "FOUND";
} else {
echo "Not Found";
}

php array skip values greater than X [duplicate]

This question already has answers here:
How to filter an array by a condition
(9 answers)
Closed 6 years ago.
I have an array with values between 1-100. However, in case of an error, is there a way to make one final check just to be sure I skip/ignore values greater than 100 and the output is between 1-100?
This is where array_filter() comes in handy.
$lower_limit = 1;
$upper_limit = 100;
$array = array_filter(
$array,
function ($value) use ($lower_limit, $upper_limit) {
return ($value >= $lower_limit && $value <= $upper_limit);
}
);
Using array_filter is a way to it.
It will iterate through your array and filters it using the supplied function. In the end you'll get an array with only elements between 1 and 100.
$arr = array(
1, 2, 99, 201,
);
$goodArr = array_filter($arr, function($value){
return ($value >= 1 && $value <= 100);
});

PHP - multidimensional array from arrays [duplicate]

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 1 year ago.
I've got 6 arrays - 1 with name and 5 with some properties - which should be assigned to that name. All values are of course in order. I'd like to make a 2-dimensional array with will be later put into CSV and the result should be as on the table here:
I guess that i have to do 2 loops here, but I can't make them work. How to construct such array?
Solution found
I've connected all arrays:
$final_array = array($nazwa_array,$new_ilosc_array,$new_koszt_array,$new_cena_lifo_array,$new_cena_fifo_array,$new_rodzaj_array);
I've found a matrix transposition function, which returns array in correct order:
function transpose($array) {
array_unshift($array, null);
return call_user_func_array('array_map', $array);
}
$a = array();
foreach ( $names AS $key => $value ) {
$a[$key]['name'] = $value;
$a[$key]['property1'] = $value.'->'.$property1_array[$key];
$a[$key]['property2'] = $value.'->'.$property2_array[$key];
$a[$key]['property3'] = $value.'->'.$property3_array[$key];
$a[$key]['property4'] = $value.'->'.$property4_array[$key];
$a[$key]['property5'] = $value.'->'.$property5_array[$key];
}

PHP: How to delete all array elements after an index [duplicate]

This question already has answers here:
php - how to remove all elements of an array after one specified
(3 answers)
Closed 9 years ago.
Is it possible to delete all array elements after an index?
$myArrayInit = array(1=>red, 30=>orange, 25=>velvet, 45=>pink);
now some "magic"
$myArray = delIndex(30, $myArrayInit);
to get
$myArray = array(1=>red, 30=>orange);
due to the keys in $myArray are not successive, I don't see a chance for array_slice()
Please note : Keys have to be preserved! + I do only know the Offset Key!!
Without making use of loops.
<?php
$myArrayInit = [1 => 'red', 30 => 'orange', 25 => 'velvet', 45 => 'pink']; //<-- Your actual array
$offsetKey = 25; //<--- The offset you need to grab
//Lets do the code....
$n = array_keys($myArrayInit); //<---- Grab all the keys of your actual array and put in another array
$count = array_search($offsetKey, $n); //<--- Returns the position of the offset from this array using search
$new_arr = array_slice($myArrayInit, 0, $count + 1, true);//<--- Slice it with the 0 index as start and position+1 as the length parameter.
print_r($new_arr);
Output :
Array
(
[1] => red
[30] => orange
[25] => velvet
)
Try
$arr = array(1=>red, 30=>orange, 25=>velvet, 45=>pink);
$pos = array_search('30', array_keys($arr));
$arr= array_slice($arr,0,$pos+1,true);
echo "<pre>";
print_r($arr);
See demo
I'd iterate over the array up until you reach the key you want to truncate the array thereafter, and add those items to a new - temporary array, then set the existing array to null, then assign the temp array to the existing array.
This uses a flag value to determine your limit:
$myArrayInit = array(1=>'red', 30=>'orange', 25=>'velvet', 45=>'pink');
$new_array = delIndex(30,$myArrayInit);
function delIndex($limit,$array){
$limit_reached=false;
foreach($array as $ind=>$val){
if($limit_reached==true){
unset($array[$ind]);
}
if($ind==$limit){
$limit_reached=true;
}
}
return $array;
}
print_r($new_array);
Try this:
function delIndex($afterIndex, $array){
$flag = false;
foreach($array as $key=>$val){
if($flag == true)
unset($array[$key]);
if($key == $afterIndex)
$flag = true;
}
return $array;
}
This code is not tested

Categories