This question already has answers here:
Finding cartesian product with PHP associative arrays
(10 answers)
Closed 7 years ago.
Initially, I am afraid, that I do not find a better title for this question.
I have a two dimensional array that looks like this, for example:
[0] => Array
(
[0] => 10,00
)
[1] => Array
(
[0] => 3
[1] => 4
)
[2] => Array
(
[0] => true
[1] => false
)
i'd like now to convert/parse this into a two dimensional array that looks like this:
[0] => Array
(
[0] => 10,00
[1] => 3
[2] => true
)
[1] => Array
(
[0] => 10,00
[1] => 4
[2] => true
)
[2] => Array
(
[0] => 10,00
[1] => 3
[2] => false
)
[3] => Array
(
[0] => 10,00
[1] => 4
[2] => false
)
i hope you see, that the result should provide all sort of possible combinations. indeed, the length of the first array can differ.
i'd be interested in how to solve this algorithmically, but at the moment i have no idea.
i am not sure, if this is as easy as it looks like. thank you in advance.
I imagine this could be refined, but it should do the trick:
<?php
$arrStart = array(
array('10,00'),
array(3, 4),
array('true', 'false')
);
$arrPositions = array();
$arrResult = array();
//get a starting position set for each sub array
for ($i = 0; $i < count($arrStart); $i++)
$arrPositions[] = 0;
//repeat until we've run out of items in $arrStart[0]
while (array_key_exists($arrPositions[0], $arrStart[0])) {
$arrTemp = array();
$blSuccess = true;
//go through each of the first array levels
for ($i = 0; $i < count($arrStart); $i++) {
//is there a item in the position we want in the current array?
if (array_key_exists($arrPositions[$i], $arrStart[$i])) {
//add that item to our temp array
$arrTemp[] = $arrStart[$i][$arrPositions[$i]];
} else {
//reset this position, and raise the one to the left
$arrPositions[$i] = 0;
$arrPositions[$i - 1]++;
$blSuccess = false;
}
}
//this one failed due to there not being an item where we wanted, skip to next go
if (!$blSuccess) continue;
//successfully adding nex line, increase the right hand count for the next one
$arrPositions[count($arrStart) - 1]++;
//add our latest temp array to the result
$arrResult[] = $arrTemp;
}
print_r($arrResult);
?>
Related
This question already has answers here:
PHP 7 overwriting an object after pushing it to array results in overwriting of all objects in that array [duplicate]
(1 answer)
PHP array_push() is overwriting existing array elements
(3 answers)
Closed 2 months ago.
and trying to add an extra row(key : value). so this is my loops:
$newarray = [];
foreach($allJobs as $allJob)
{
for($i = 0; $i < 2 ; $i++){
$allJob->bku = $i;
$newarray[] = $allJob;
}
}
output now:
Array
(
[0] => stdClass Object
(
[id] => CFF9B1A6-37B8-4000-B058-03DC648B5289
[name] => Kreditor rapporter til RE pkt. 5
[bku] => 1
)
[1] => stdClass Object
(
[id] => CFF9B1A6-37B8-4000-B058-03DC648B5289
[name] => Kreditor rapporter til RE pkt. 5
[bku] => 1
)
but as you can se the last key value pair is the same - [bku] => 1;
What I want:
Array
(
[0] => stdClass Object
(
[id] => CFF9B1A6-37B8-4000-B058-03DC648B5289
[name] => Kreditor rapporter til RE pkt. 5
[bku] => 0
)
[1] => stdClass Object
(
[id] => CFF9B1A6-37B8-4000-B058-03DC648B5289
[name] => Kreditor rapporter til RE pkt. 5
[bku] => 1
)
So it increment my extra row bku in the nested loop.
So I found a solution:
I had convert it from stdClass object to an array, and I did it like this:
$array = json_decode(json_encode($allJobs), true);
$newarray = [];
foreach($array as $allJob) {
for($i = 0; $i < 2 ; $i++){
$allJob['bku'] = $i;
$newarray[] = $allJob;
}
}
Then it count correct in my nested loop.
I have a multidimensional array. I want to get array element which value is greater than 2 and less than 17. My Array is given below:
Array
(
[4] => Array
(
[0] => 17
[1] => 15
[2] => 12
)
[5] => Array
(
[0] => 16
)
[2] => Array
(
[0] => 3
[1] => 1
)
[1] => Array
(
[0] => 2
)
)
I want output like below:
Array
(
[4] => Array
(
[0] => 17
[1] => 15
[2] => 12
)
[5] => Array
(
[0] => 16
)
[2] => Array
(
[0] => 3
[1] => 1
)
)
Please help me how can I do it easy & fast method.
You can use a nested array filter.
$result = array_filter($outer_array, function($inner_array) {
return array_filter($inner_array, function($number) {
return $number > 2 && $number < 17;
});
});
Then inner array filter will result in an empty array being passed to the outer array filter if no values are found in the specified range. The empty array will evaluate to false in the outer filter callback, eliminating that array from the result.
Demo at 3v4l.org.
Generally, we want you to show what you have tried before we'll write code for you, but this one's on the house. For future reference, include some code snippets along with your question to avoid getting downvoted.
$output = array();
for($i = 0; $i < count($arr); $i++)
{
$use = false;
for($j = 0; $j < count($arr[$i]); $j++)
{
if($arr[$i][$j] > 2 and $arr[$i][$j] < 17)
{
$use = true;
break;
}
}
if($use)
$output[] = $arr[$i];
}
return $output;
I have 2 arrays
array 1: Array ( [0] => Merc [1] => # [2] => BM [3] => & [4] => Lotus )
array 2: Array ( [0] => 6740 [1] => 4565 [2] => 3423 )
The goal is to combine the 2 arrays and end up with:
$result = ['Merc' => 6740, 'BM' => 4565, 'Lotus' => 3423];
There is a fair amount of guidance on this already, I know, and I have read up on it but array manipulation is new to me and somehow I just cannot get my head around the logic and syntax.
Please could someone with an experienced eye tell me where I am going wrong.
I have tried:
...
//// lets echo the arrays to make sure they are correct
print_r($car);?><br><?php
print_r($part);?><br><?php
//// lets combine the 2 arrays to get an associative array
$result = [];
for($i = 0; $i < count($car); $i++){
if (($car[$i] == "&")||($car[$i] == "#")){
$i = ($i + 1);
}
foreach($car as $car) {
foreach($part as $part) {
$result[] = array(
$car => $part,
);
}
}
}
print_r($result);
The output for this is:
Array ( [0] => Array ( [Merc] => 6740 ) [1] => Array ( [BM] => 4565 ) [2] => Array ( [Lotus] => 3423 ))
The special characters to be stripped will only ever be # or &
Filter out the unwanted elements and combine them.
Code: (Demo)
$cars=['Merc','#','BM','&','Lotus'];
$parts=[6740,4565,3423];
$cars=array_diff($cars,['#','&']);
var_export(array_combine($cars,$parts));
Output:
array (
'Merc' => 6740,
'BM' => 4565,
'Lotus' => 3423,
)
p.s. You could also filter with ctype_alpha() like this: (Demo)
$cars=array_filter($cars,'ctype_alpha'); // only retain elements that are fully comprised of letters
There is an array containing K elements. What's the best way to get chunks of N < K items from this array?
Example input:
$x = [1,2,3,4,5,6,7,8,9,10]; // K = 10
Desired result, when N = 3;
$x1 = [1,2,3];
$x2 = [4,5,6];
$x3 = [7,8,9];
$x4 = [10];
Obviously, there is no need to store the result in variables. As long as it's possible to process it by foreach (or any other iteration logic), it should be fine.
The problem with array_slice is that it does not remove the N-slice from the beginning of the array. The problem with array_shift is that it does not support shifting more than 1 item at once. Is there anything more elegant than iterating over array_shift?
array_chunk is what you need.
<?php
$x = [1,2,3,4,5,6,7,8,9,10];
print_r(array_chunk($x,3));
OUTPUT :
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[0] => 4
[1] => 5
[2] => 6
)
[2] => Array
(
[0] => 7
[1] => 8
[2] => 9
)
[3] => Array
(
[0] => 10
)
)
Look into array_chunk -> http://www.w3schools.com/php/func_array_chunk.asp
$x = [1,2,3,4,5,6,7,8,9,10];
print_r(array_chunk($x,3,true));
or you could do it this way -
$x = [1,2,3,4,5,6,7,8,9,10];
$chunks = array();
while(count($x)){
$chunks[] = array_splice($x, 0,3,array());
$i++;
}
Could someone tell me which method would be more efficient?
array_chunk function is used to create sub arrays of equal size.
E.g.
$a=array_chunk($array,3);
I'm building a "nested" array fetching from database; here's my script:
while ($row_rsMaster = mysql_fetch_assoc($rsMaster)) {
$numbers[] = array("Page ");
}
I'd like to obtain the following array (with print_r() function), but I'm totally stuck on how to get the page number:
Array
(
[0] => Array
(
[0] => Page 1
[1] => 1
)
[1] => Array
(
[0] => Page 2
[1] => 2
)
[2] => Array
(
[0] => Page 3
[1] => 3
)
[3] => Array
(
[0] => Page 4
[1] => 4
)
)
I tried:
$numbers[] = array("Pagina " . key($numbers)+1, key($numbers)+1);
but it didn't lead to expected results (in my mind, it should get the current key number of the "parent" array and increment by 1)
Please, any help?
Thanks in advance
Just count by your own:
$n = 0;
while ($row_rsMaster = mysql_fetch_assoc($rsMaster)) {
$n++;
$numbers[] = array("Page ".$n, $n);
}
Or, use count($numbers)+1 in your code:
while ($row_rsMaster = mysql_fetch_assoc($rsMaster)) {
$numbers[] = array("Page ".(count($numbers)+1), count($numbers)+1);
}
Thanks to datacompboy I finally came to this:
while ($row_rsMaster = mysql_fetch_assoc($rsMaster)) {
$counter = count($numbers)+1;
$numbers[] = array("Page " . $counter, $counter);
}