Getting parent key in a nested array - php

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);
}

Related

php split array on change of value in column data

I am trying to split array data into multiple arrays based on change in data value at known position (column).
$input = array(
array(1,2,3),
array(4,5,3),
array(7,8,4),
array(9,10,4),
array(11,12,4)
);
Here column 3 changes values from 3 to 4
and expected result is to have 2 arrays
$out1 = array(array(1,2,3),array(4,5,3));
$out2 = array(array(7,8,4), array(9,10,4), array(11,12,4));
since number of rows are variable, cannot use array_chunk
since column 3 values are variable, cannot use array_filter
number of output arrays are also variable.
trying splice but failing...
You can use array_reduce to make new array, where index will be equal to last numbers in items
$new = array_reduce($input, function($c, $x) { $c[$x[2]][] = $x; return $c; }, [] );
$out1 = $new[3];
$out2 = $new[4];
demo
But if array is not sorted and you want to split at points of changing that number, the code can be
$i = -1;
$last = null;
$new = [];
foreach($input as $x) {
if ($x[2] != $last) {
$i++;
$last = $x[2];
}
$new[$i][] = $x;
}
demo
You can use split index with index of array,
$out1 = $out2 = [];
$splitIndex = 2;
foreach($input as $k => $v){
if($k < $splitIndex){
$out1[] = $v;
}else{
$out2[] = $v;
}
}
print_r($out1);
print_r($out2);
Working demo
Output:-
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[0] => 4
[1] => 5
[2] => 3
)
)
Array
(
[0] => Array
(
[0] => 7
[1] => 8
[2] => 4
)
[1] => Array
(
[0] => 9
[1] => 10
[2] => 4
)
[2] => Array
(
[0] => 11
[1] => 12
[2] => 4
)
)

PHP - get array element between a range in multidimensional array

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;

How to create a permutation of two dimensional array [duplicate]

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);
?>

Building a recursive function to create a multidimensional array

I think what I want is a recursive function, but please let me know if there's another way to achieve what I want to do! I'm not sure I'm going to explain this very well, so please let me know if you need further clarification.
I've got a function, findSeed() which takes an id and returns an array that contains information about the "seed":
function findSeeds($id) {
global $wpdb;
$query = "SELECT * FROM seedTable WHERE id = " . $id;
$seed = $wpdb->get_row($query, ARRAY_A);
return $seed;
}
It returns the following array:
Array
(
[id] => 9
[name] => Sign
[seed1] => 4
[seed2] => 3
)
Where seed 1 and seed 2 are the ids of the seeds needed to create it. I'm looking to make a function that will create a multidimensional array, in the following format, where the first part of the array contains the first "seed", the next contains the two seeds contained in the first, the next contains the two seeds contained in each of those, and so on:
Array
(
[1] => Array
(
[0] => Stripey Wallpaper
)
[2] => Array
(
[0] => Green Block
[1] => Aqua Block
)
[3] => Array
(
[0] => Bricks
[1] => Grass
[2] => Bricks
[3] => Glass Pane
)
[4] => Array
(
[0] => Rock
[1] => Grass
[2] => Dirt
[3] => Rock
[4] => Rock
[5] => Grass
[6] => Rock
[7] => Lava
)
)
I'm doing it so far with a (horrible) function, shown here, but the "map" could be anything between 2 and 8 rows, and I'm struggling to see how to turn it into a neat little function that works for anything:
function makeMap($id) {
// First Row
$rowNum = 1;
$oneSeed = findSeeds($id);
$map[$rowNum][] = $oneSeed[name];
// Second Row
$rowNum = $rowNum + 1;
$twoSeed = findSeeds($oneSeed[seed1]);
$threeSeed = findSeeds($oneSeed[seed2]);
$map[$rowNum][] = $twoSeed[name];
$map[$rowNum][] = $threeSeed[name];
// Third Row
$rowNum = $rowNum + 1;
$fourSeed = findSeeds($twoSeed[seed1]);
$fiveSeed = findSeeds($twoSeed[seed2]);
$sixSeed = findSeeds($threeSeed[seed1]);
$sevenSeed = findSeeds($threeSeed[seed2]);
$map[$rowNum][] = $fourSeed[name];
$map[$rowNum][] = $fiveSeed[name];
$map[$rowNum][] = $sixSeed[name];
$map[$rowNum][] = $sevenSeed[name];
// Fourth Row
$rowNum = $rowNum + 1;
$eightSeed = findSeeds($fourSeed[seed1]);
$nineSeed = findSeeds($fourSeed[seed2]);
$tenSeed = findSeeds($fiveSeed[seed1]);
$elevenSeed = findSeeds($fiveSeed[seed2]);
$twelveSeed = findSeeds($sixSeed[seed1]);
$thirteenSeed = findSeeds($sixSeed[seed2]);
$fourteenSeed = findSeeds($sevenSeed[seed1]);
$fifteenSeed = findSeeds($sevenSeed[seed2]);
$map[$rowNum][] = $eightSeed[name];
$map[$rowNum][] = $nineSeed[name];
$map[$rowNum][] = $tenSeed[name];
$map[$rowNum][] = $elevenSeed[name];
$map[$rowNum][] = $twelveSeed[name];
$map[$rowNum][] = $thirteenSeed[name];
$map[$rowNum][] = $fourteenSeed[name];
$map[$rowNum][] = $fifteenSeed[name];
return $map;
}
It should stop when all the "row" nodes are blank, so the following only needs to return the first two "rows":
Array
(
[1] => Array
(
[0] => Wood Block
)
[2] => Array
(
[0] => Dirt
[1] => Lava
)
[3] => Array
(
[0] =>
[1] =>
[2] =>
[3] =>
)
[4] => Array
(
[0] =>
[1] =>
[2] =>
[3] =>
[4] =>
[5] =>
[6] =>
[7] =>
)
)
Any tips, hints or solutions would be GREATLY appreciated,
Thank you.
Edit: Quick note on why I'd like it in the above format - I'm then printing out the results in a table, with the first seed spanning the entire row, then breaking it down with the children underneath, like so:
$map = makeMap($_POST['theItem']);
$colspan = count(end(array_values($map)));
echo '<h3>' . $map[row1][0] . '</h3><br/>';
echo '<table>';
foreach ($map as $row) {
echo '<tr>';
foreach ( $row as $cell) {
echo '<td colspan="'. $colspan .'"><div class="seed">' . $cell . '</div></td>';
}
$colspan = $colspan / 2;
echo '</tr>';
}
echo '</table>';
<?php
$array = array('one', 'two', 'three');
for($i =1; $i<= count($array); $i++){
for($j=0; $j<$i; $j++){
$arrymulti[$i][$j]= $array[$j];
}
}
echo '<pre>';
print_r($arrymulti);
?>
Output:
Array
(
[1] => Array
(
[0] => one
)
[2] => Array
(
[0] => one
[1] => two
)
[3] => Array
(
[0] => one
[1] => two
[2] => three
)
)
DEMO
You can Use this recursive function That I Wrote It For Class
static public $map;
static function seeder($id,$Depth=0){
$Seed=findSeeds($id);
if(!$Seed){
return self::$map;
}
self::$map[$Depth][]=$Seed['name'];
self::seeder($Seed['seed1'],$Depth+1);
self::seeder($Seed['seed2'],$Depth+1);
if($Depth==0){
foreach(self::$map as $k=>$v){
$Flag=true;
foreach($v as $key=>$Value){
if($Value!="")$Flag=false;
}
if($Flag){
for($i=$k;$i<=count(self::$map);$i++){
#unset(self::$map[$i]);
}
break;
}
}
}
return self::$map;
}
Sample
print_r(seeder($ID));
The output Is similar of Your sample

Filling php array that has missing values

I've a series of arrays with values that goes from 1 to 5. Almost every array has missing values, some even dont have any values. My objective is to fill the missing values with 0. All those arrays are stored into a multidimensional array.
My array looks like:
Array
(
[1] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[2] => Array
(
[0] => 1
[1] => 5
)
[3] => Array
(
[0] => (this array has no values)
)
[4] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
etc...
)
How it should be:
Array
(
[1] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 0
[4] => 0
)
[2] => Array
(
[0] => 1
[1] => 0
[2] => 0
[3] => 0
[4] => 5
)
[3] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
[4] => 0
)
[4] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
etc...
)
Any help would be appriciated!
For each of your subarrays loop through the numbers 1 to 5, and if that value exists set its key to be one less than its value:
$newarray = array();
foreach($arr as $key => $subarr) {
for ($i = 1; $i <= 5; $i++) {
if (in_array($i, $subarr)) $newarray[$key][$i - 1] = $i;
else $newarray[$key][$i - 1] = 0;
}
}
Where $newarray is your output and $arr is your input array.
You may want to note that PHP does not truly do multidimensional arrays. It only allows you to relate 2 flat arrays together which is not true multidimensionality.
This does not work and will produce results described above.
$menu[1] = "My Training"; //not $menu[1][0]
$menu[1][1] = "To Do List";
$menu[1][2] = "Catalog";
$menu[1][3] = "Self-Report";
$menu[1][4] = "Completions";
$menu[2] = "Manager";
$menu[2][1] = "Direct Reports";
$menu[2][2] = "Incompletes";
$menu[2][3] = "Completions";
$menu[3] = "Instructor";
$menu[3][1] = "My Classes";
$menu[3][2] = "Printables";
$menu[3][3] = "Qualifications";
This does work.
$menu[1] = "My Training"; //not $menu[1][0]
$submenu[1][1] = "To Do List";
$submenu[1][2] = "Catalog";
$submenu[1][3] = "Self-Report";
$submenu[1][4] = "Completions";
$menu[2] = "Manager";
$submenu[2][1] = "Direct Reports";
$submenu[2][2] = "Incompletes";
$submenu[2][3] = "Completions";
$menu[3] = "Instructor";
$submenu[3][1] = "My Classes";
$submenu[3][2] = "Printables";
$submenu[3][3] = "Qualifications";
$submenu is only related to $menu through the first key number as there are no first dimension values to $submenu.
Something like this (array_pad() won't do the trick). $myArray is your source array. Completed array is returned in $result:
$result = array();
foreach( $myArray as $subKey=>$subArray ) {
for( $i=0; $i<5; $i++ ) {
if( isset( $subArray[$i] )) {
$result[$subKey][$i] = $subArray[$i];
} else {
$result[$subKey][$i] = 0;
}
}
}
Note, we do copy of the array. You cannot fill array in-place.
It's been many years since I wrote any PHP but something like this might do the trick I guess?
for($i = 0; $i < 5; $i++)
{
if(empty($myArray[$i])
{
$myArray[$i] = 0;
}
}

Categories