I can't quite seem to grasp how I would go about combining the indexes in this array. Below is an example of the array. Any help, resources, or direction would be appreciated.
$array_one = array(
10 => array(0 => 2/3-AM),
10 => array(0 => AUT-PR),
1195 => array(0 => 1/2-AM),
1258 => array(0 => GR-1),
1195 => array(0 => 1/7-PM),
);
I'd like for it to look like this:
$array_one = array(
10 => array(0 => 2/3-AM, AUT-PR),
1195 => array(0 => 1/2-AM, 1/7-PM),
1258 => array(0 => GR-1),
);
var_dump
Making assumptions from your screenshot, I think you meant your input array is:
$input = array(
array(10 => array(0 => '2/3-AM')),
array(10 => array(0 => 'AUT-PR')),
array(1195 => array(0 => '1/2-AM')),
array(1258 => array(0 => 'GR-1')),
array(1195 => array(0 => '1/7-PM')),
);
To get this into your target format:
$output = [];
foreach ($input as $keys) {
foreach ($keys as $key => $values) {
foreach ($values as $value) {
$output[$key][] = $value;
}
}
}
var_dump($output);
This results in:
array(3) {
[10]=> array(2) {
[0]=> string(6) "2/3-AM"
[1]=> string(6) "AUT-PR"
}
[1195]=> array(2) {
[0]=> string(6) "1/2-AM"
[1]=> string(6) "1/7-PM"
}
[1258]=> array(1) {
[0]=> string(4) "GR-1"
}
}
Related
I want to get all rows (in descending order) which have a "score" in the top five of all scores. Because there may be ties, it is possible that there will be more than 5 rows in the result array.
I have an array in PHP :
Array
(
[0] => Array([number] => 1162)
[1] => Array([number] => 1162)
[2] => Array([number] => 1158)
[3] => Array([number] => 1157)
[4] => Array([number] => 1157)
[5] => Array([number] => 1130)
[6] => Array([number] => 1117)
[7] => Array([number] => 1097)
[8] => Array([number] => 1086)
)
I want the rows with the top 5 ranks. The final output contains 7 rows because of ties:
Array
(
[0] => Array([number] => 1162) #1 Rank
[1] => Array([number] => 1162) #1 Rank
[2] => Array([number] => 1158) #2 Rank
[3] => Array([number] => 1157) #3 Rank
[4] => Array([number] => 1157) #3 Rank
[5] => Array([number] => 1130) #4 Rank
[6] => Array([number] => 1117) #5 Rank
)
How can I achieve this? This array value data can be changed according to the situation.
You first need to order the array Desc. Adjust how much ranking you want using the variable $limit.
<?php
$limit = 5;
$arr = array();
$arr[] = array('number' => 1162);
$arr[] = array('number' => 1162);
$arr[] = array('number' => 1158);
$arr[] = array('number' => 1157);
$arr[] = array('number' => 1157);
$arr[] = array('number' => 1130);
$arr[] = array('number' => 1117);
$arr[] = array('number' => 1097);
$arr[] = array('number' => 1086);
function sortByOrder($a, $b) {
return $b['number'] - $a['number'];
}
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['number'] === $id) {
return true;
}
}
return false;
}
usort($arr, 'sortByOrder');
$new_arr = array();
$i = 0;
foreach($arr as $key => $value){
$checkDuplicate = searchForId($value['number'], $new_arr);
if(!$checkDuplicate){
$i++;
}
if($i > $limit){
break;
}
$new_arr[] = $value;
}
var_dump($new_arr);
Result:
array(7) {
[0]=>
array(1) {
["number"]=>
int(1162)
}
[1]=>
array(1) {
["number"]=>
int(1162)
}
[2]=>
array(1) {
["number"]=>
int(1158)
}
[3]=>
array(1) {
["number"]=>
int(1157)
}
[4]=>
array(1) {
["number"]=>
int(1157)
}
[5]=>
array(1) {
["number"]=>
int(1130)
}
[6]=>
array(1) {
["number"]=>
int(1117)
}
}
Demo: https://sandbox.onlinephpfunctions.com/c/49751
Because you array of rows are consistently formatted, you can simply call rsort() to natively sort the data in a descending fashion.
Next iterate the sorted array and maintain an incremented "counter" variable ($rank) -- only increase this value when a new $number is encountered. So long as the rank of the current number is less than on equal to the $maxRank, push the $number into the result array. In other words, when the current rank exceeds the max rank, do not push any more numbers into the result and stop iterating.
Code: (Demo)
$array = [
['number' => 1117],
['number' => 1097],
['number' => 1162],
['number' => 1158],
['number' => 1162],
['number' => 1157],
['number' => 1086],
['number' => 1157],
['number' => 1130],
];
$maxRank = 5;
rsort($array); // sort DESC
$rank = 0;
$result = [];
foreach ($array as ['number' => $number]) {
$ranks[$number] ??= ++$rank;
if ($ranks[$number] > $maxRank) {
break;
}
$result[] = $number;
}
var_export($result);
Output:
array (
0 => 1162,
1 => 1162,
2 => 1158,
3 => 1157,
4 => 1157,
5 => 1130,
6 => 1117,
)
To see how the ranks are distributed without the break, see this demo.
This question already has answers here:
How would combine multiple exploded lists created by foreach into one array? [duplicate]
(4 answers)
Closed 7 months ago.
I have 2 arrays that are coming from the database, [options] column has comma-separated values.
Array
(
[0] => Array
(
[id] => 143
[menu_id] => 590
[name] => bread
[options] => small, large
)
[1] => Array
(
[id] => 144
[menu_id] => 590
[name] => jam
[options] => mango, orange, grape
)
)
Is there have any way to combine the list of [options] at [0] and [1]?
Example: small, large, mango, orange, grape
Approach
<?php foreach ($menu_options as $key => $menu_option) : ?>
<?PHP $exploded_variant_options = explode(',', $menu_option['options']);
foreach ($exploded_variant_options as $exploded_variant_option) : ?>
<?php echo ucfirst(sanitize($exploded_variant_option)); ?> //print one by one
<?php endforeach; ?>
<?php endforeach; ?>
My suggestion would be to use array_merge. The code would look like this:
<?php
$all_options = [];
foreach( $menu_options as $key => $menu_option ) {
$all_options = array_merge($all_options, explode(", ", $menu_option["options"]));
}
?>
if this is your array :
$arrays = array (
array( 'id' => 143, 'menu_id' => 590, 'name' => 'bread', 'options' => 'small,large'),
array( 'id' => 144, 'menu_id' => 590, 'name' => 'jam', 'options' => 'mango,orange,grape')
);
you can use array_map for achieving that :
function spliter($key, $value){
if($key == 'options')
return $value = explode(',', $value);
else
return $value;
}
foreach($arrays as &$array)
$array = array_map( 'spliter' , array_keys($array), $array);
then this will be a dump of your $arrays :
array(2) {
[0]=>
array(4) {
[0]=>
int(143)
[1]=>
int(590)
[2]=>
string(5) "bread"
[3]=>
array(2) {
[0]=>
string(5) "small"
[1]=>
string(5) "large"
}
}
[1]=>
&array(4) {
[0]=>
int(144)
[1]=>
int(590)
[2]=>
string(3) "jam"
[3]=>
array(3) {
[0]=>
string(5) "mango"
[1]=>
string(6) "orange"
[2]=>
string(5) "grape"
}
}
}
If you just want to print out all the options (insertion order) and not modify them further, you could also just call this:
<?php
$arr = [
['id' => 143, 'menu_id' => 590, 'name' => 'bread', 'options' => 'small, large'],
['id' => 144, 'menu_id' => 590, 'name' => 'jam', 'options' => 'mango, orange, grape']
];
var_dump(array_reduce(array_column($arr, 'options'), function ($c, $i) {
return $c ? "${c}, ${i}" : $i;
}));
// prints: string(34) "small, large, mango, orange, grape"
?>
Otherwise, I suggest using the approach shown by "Teodor".
i've got this array (from a csv file) :
array (
0 => 'entity_id;commission_book;old_price;new_price',
1 => '667;667;667;667',
2 => '668;668;668;668'
)
How to build a new array that looks like :
[0] : (
'entity_id' => '667',
'commission_book' => '667',
'old_price' => '667',
'new_price' => '667',
);
[1] : (
'entity_id' => '668',
'commission_book' => '668',
'old_price' => '668',
'new_price' => '668',
)
In other words, i want to buid 2 objects using the first array, is there any way to perfom that please ? I'm trying for hours now
This is a simply but elegant way to do that:
<?php
$input = [
0 => 'entity_id;commission_book;old_price;new_price',
1 => '667;667;667;667',
2 => '668;668;668;668'
];
$output = [];
// drop header entry
array_shift($input);
// process remaining entries
foreach ($input as $key=>$entry) {
$x = &$output[$key];
list(
$x['entity_id'],
$x['commission_book'],
$x['old_price'],
$x['new_price']
) = explode(';', $entry);
}
print_r($output);
The output of the above is:
Array
(
[0] => Array
(
[new_price] => 667
[old_price] => 667
[commission_book] => 667
[entity_id] => 667
)
[1] => Array
(
[new_price] => 668
[old_price] => 668
[commission_book] => 668
[entity_id] => 668
)
)
Short solution with array_slice and array_combine:
$from_csv = [
0 => 'entity_id;commission_book;old_price;new_price',
1 => '667;667;667;667',
2 => '668;668;668;668'
];
$result = [];
$keys = explode(";", $from_csv[0]); // header fields
foreach(array_slice($from_csv, 1) as $v){
$result[] = array_combine($keys, explode(";", $v));
}
echo '<pre>';
var_dump($result);
// the output:
array(2) {
[0]=>
array(4) {
["entity_id"]=>
string(3) "667"
["commission_book"]=>
string(3) "667"
["old_price"]=>
string(3) "667"
["new_price"]=>
string(3) "667"
}
[1]=>
array(4) {
["entity_id"]=>
string(3) "668"
["commission_book"]=>
string(3) "668"
["old_price"]=>
string(3) "668"
["new_price"]=>
string(3) "668"
}
}
$array = array(
0 => 'entity_id;commission_book;old_price;new_price',
1 => '667;667;667;667',
2 => '668;668;668;668');
$array[0] = explode(";",$array[0]);
$array[1] = explode(";",$array[1]);
$array[2] = explode(";",$array[2]);
$newarray = array();
for ($i=0;$i<count($array[0]);$i++){
$newarray[0][$array[0][$i]] = $array[1][$i];
$newarray[1][$array[0][$i]] = $array[2][$i];
}
echo "<pre>";
var_dump($array);
var_dump($newarray);
echo "</pre>";
Is there a specific function to move array which is in array to the parent array as key or value.
array(5) { [0]=> array(1) { [0]=> string(2) "id" } [1]=> array(1) { [0]=> string(7)
"buydate" } [2]=> array(1) { [0]=> string(6) "expire" } [3]=> array(1) { [0]=> string(6)
"planid" } [4]=> array(1) { [0]=> string(5) "buyer" } }
Result I would like to get is:
array() { [0] => 'id', [1] => 'buydate' etc. }
Or
array('id', 'buydate' etc.. )
Is it possible to achieve without foreach ?
array_map() is extremely powerful and should do the trick:
$array = ... ; // your initial array
$flattened_array = array_map(function($item) {
return $item[0];
}, $array);
If you want to flatten the desired array, and use foreach you can do it this way.
Consider this example:
// Sample data:
$values = array(
0 => array(
0 => 'id',
),
1 => array(
0 => 'buydate',
),
2 => array(
0 => 'expire',
),
3 => array(
0 => 'planid',
),
4 => array(
0 => 'buyer',
),
);
$new_values = array();
foreach($values as $key => $value) {
$new_values[] = $value[0];
}
print_r($new_values);
Sample Output:
Array
(
[0] => id
[1] => buydate
[2] => expire
[3] => planid
[4] => buyer
)
Or alternatively, you can you the iterator. Consider this example:
$new_values = array();
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($values));
foreach($iterator as $value) {
$new_values[] = $value;
}
It should gave you the same output.
Let's say I have an array:
$myArray = array('alfa' => 'apple', 'bravo' => 'banana', 'charlie' => 'cherry', 'delta' => 'danjou pear');
I want to search it for certain keys and if found replace the values of those according to this other array:
$myReplacements = array('bravo' => 'bolognese', 'lie' => 'candy');
I know I can do this:
function array_search_replace($haystack, $replacements, $exactMatch = false) {
foreach($haystack as $haystackKey => $haystackValue) {
foreach($replacements as $replacementKey => $replacementValue) {
if($haystackKey == $replacementKey || (!$exactMatch && strpos($haystackKey, $replacementKey) !== false)) {
$haystack[$haystackKey] = $replacementValue;
}
}
}
return $haystack;
}
But, is there really no smarter/faster way to do it?
EDIT: I also need to be able to search for keyparts, so that 'lie' and 'charlie' results in a match.
EDIT2: Expected results are:
var_dump(array_search_replace($myArray, $myReplacements));
array(4) { ["alfa"]=> string(5) "apple" ["bravo"]=> string(9) "bolognese" ["charlie"]=> string(5) "candy" ["delta"]=> string(11) "danjou pear" }
var_dump(array_search_replace($myArray, $myReplacements, true));
array(4) { ["alfa"]=> string(5) "apple" ["bravo"]=> string(9) "bolognese" ["charlie"]=> string(6) "cherry" ["delta"]=> string(11) "danjou pear" }
You can use the PHP's array_replace function.
Also, array_merge does something similar.
In your code:
$finalArray = array_replace($myArray, $myReplacements);
Full PHP Code
<?php
$myArray = array('alfa' => 'apple', 'bravo' => 'banana', 'charlie' => 'cherry', 'delta' => 'danjou pear');
$myReplacements = array('bravo' => 'bolognese', 'lie' => 'candy');
$finalArray = array_replace($myArray, $myReplacements);
print_r($finalArray);
?>
Output
Array
(
[alfa] => apple
[bravo] => bolognese
[charlie] => cherry
[delta] => danjou pear
[lie] => candy
)
Fiddle here: http://codepad.viper-7.com/60o5xT
Is this what you need ?
<?php
$myArray = array('alfa' => 'apple', 'bravo' => 'banana', 'charlie' => 'cherry', 'delta' => 'danjou pear');
$myReplacements = array('bravo' => 'bolognese', 'lie' => 'candy');
print_r(array_merge($myArray, $myReplacements));
?>
Output:
Array
(
[alfa] => apple
[bravo] => bolognese
[charlie] => cherry
[delta] => danjou pear
[lie] => candy
)
Using array_merge
Arrays in PHP are hashes, you don't need to search for a key, you can access it in O(1) time.
$myArray = array('alfa' => 'apple', 'bravo' => 'banana', 'charlie' => 'cherry', 'delta' => 'danjou pear');
$myReplacements = array('bravo' => 'bolognese', 'lie' => 'candy');
var_dump($myArray);
foreach($myReplacements as $k => $v) {
if(array_key_exists($k, $myArray)) {
$myArray[$k] = $v;
}
}
var_dump($myArray);
Output:
array(4) {
["alfa"]=>
string(5) "apple"
["bravo"]=>
string(6) "banana"
["charlie"]=>
string(6) "cherry"
["delta"]=>
string(11) "danjou pear"
}
array(4) {
["alfa"]=>
string(5) "apple"
["bravo"]=>
string(9) "bolognese"
["charlie"]=>
string(6) "cherry"
["delta"]=>
string(11) "danjou pear"
}
you can use the following code to directly replace the matching key
<?php
$base = array("orange", "banana", "apple", "raspberry");
$replacements = array(0 => "pineapple", 4 => "cherry");
$replacements2 = array(0 => "grape");
$basket = array_replace($base, $replacements, $replacements2);
print_r($basket);
?>
output:
Array
(
[0] => grape
[1] => banana
[2] => apple
[3] => raspberry
[4] => cherry
)