PHP: Fill multidimensional array at specific positions recursively - php

I need to fill a multidimensional array with simple arrays recursively at positions specified by for loops, and that need to be done with the same multidimensional array.
The first time the multid. array is filled is in the code below
$vector_provisor = array ();
for ($i = 0; $ i <variable_variable; $i++)
{
array_push($vector_temp, 0);
}
$ element_pivot =$ lines [$index_line_pivot] [$index_column_pivo];
for ($j = 0, $j <dim - 1, j++)
{
$value = $rows [$index_line_pive] [$j] / $element_pivot;
array_push ($vector_provisor, $ value);
$index = array ($index_line_pivot);
}
#that's the array filled:
$new_lines {$index} = array_fill_keys ($index, $vector_provisor);
Now let's say the first time it filled position [1], if I try to repeat that, in another for loop, for positions [1] and [2], but without creating the array again, it simply empties all the positions and I got an empty array.
What could I do?

Related

Convert One dimentional Array to Multidimentional array in PHP

In PHP I have a dynamic 1-D Array which is like
$array = ['test1', 'test2', ..., 'testn'] And I need to convert this into a multidimensional array where array nesting level will be equal to the number of elements in the 1-D array, and each level will have its index with the name of 1-D array values, so, the output should be something like:
$multidimentional['test1']['test2'][...]['testn'] = [Some Fixed Value] And, after creating the multidimensional array assign a fixed value to it.
So, basically this fixed value needs to be assigned in a multidimensional array which has nesting level as per 1-D array values.
You can simply loop over the elements, assign the element as key to the current array and move on with the child array.
<?php
$array = ['test1', 'test2','test3', 'test4'];
$res = [];
$temp = &$res;
foreach($array as $val){
$temp[$val] = [];
$temp = &$temp[$val];
}
$temp[] = 45; // some fixed value
print_r($res);
Demo: https://3v4l.org/INfR2

Combining two arrays using the first array as key(but has duplicates) then adding the second array values that has the matching duplicates

I want to combine two arrays. First use the first array as the key(combining the duplicates) then add the values from the second array to adjust to the specific keys
//first array
array('1','0','1');
//second array
array('50','10','20');
//output -> first array ('1','0') second array -> ('70','10')
removing the duplicates in the first array and adding the corresponding "duplicate" key in the second array values
Use a result array to collect the outcomes like this:
//first array
$k = array('1','0','1');
//second array
$v = array('50','10','20');
$result = array();
foreach($k as $index => $value) {
if(!isset($result[$value])) {
$result[$value] = 0;
}
$result[$value] += $v[$index];
}
print_r($result);

randomly subtract desired percentage from a array using php

I have a array which contains 40 elements like this
$i = array('1','2','3','4','5','6','7','8','9','10','11',
'12','13','14','15','16','17','18','19','20','21','22','23','24',
'25','26','27','28','29','30','31','32','33','34','35',
'36','37','38','39','40');
now i have 4 variations like 5%, 10%, 15%, 20%
The requirement is i need to take array values randomly after subtracting the desired variation.
Lets say i used 5% variation so i need to separate 5% from the array ie 2 elements i need to remove randomly from the array and keep the rest 38 element in a new array randomly.so both the resulted array as well subtracted elements need to be in two different array.
I need a function with two parameter ie one is variation and another is required array ie resultant array or subtracted elements array.
This same sequence follows to all other variations.
Although I am not sure what you mean by rest 38 element in a new array randomly e.g. does this mean the new array is also shuffled? This is what I came up with.
<?php
function splitArray($variation, $array) {
$count = count($array); // Count the elements in the given array
$removeNumber = floor($count*($variation/100)); // Calculate the number of elements to remove
// Create an array holding the index numbers for splicing, these numbers are random.
for($i=0; $i<$removeNumber; $i++) {
$removeArray[] = rand(0,$count-1);
}
// Loop through the removeArray to retrieve the indexes to splice at.
for($i=0; $i<count($removeArray); $i++) {
$subArray[] = $array[$removeArray[$i]];
array_splice($array, $removeArray[$i], 1);
}
// return the newly spliced array and the spliced items array
return array($array, $subArray);
}
$oldArray = array('1','2','3','4','5','6','7','8','9','10','11',
'12','13','14','15','16','17','18','19','20','21','22','23','24',
'25','26','27','28','29','30','31','32','33','34','35',
'36','37','38','39','40');
$array = splitArray(5, $oldArray);
$subArray = $array[0];
$newArray = $array[1];
<?php
function subtractFromArray($array,$percentage){
//Randonmising the array
shuffle($array);
//percentage numeric equivalent wrt array aize
$substract_variation_count = floor(sizeof($array) * $percentage/100);
//New extracted array
$new_array = array_slice($array,$substract_variation_count);
//retuns the new array with 38 elements
return $new_array;
}
//array with all elements
$array = array('1','2','3','4','5','6','7','8','9','10','11',
'12','13','14','15','16','17','18','19','20','21','22','23','24',
'25','26','27','28','29','30','31','32','33','34','35',
'36','37','38','39','40');
//get new array
$new_array = subtractFromArray($array,5);
//print new array
print_r($new_array);
//Substracted array with 2 elements
$substrcated_array = array_diff($array,$new_array);
print_r($substrcated_array);
?>

PHP: Remove all but the last two element from an associative array

I have the following string: "Bikes->Hardtails->XC". I'm exploding the array on the "->" characters to split the individual words in to elements in an associative array. If the array has more two elements, I'm attempting to remove all array elements prior to the last two elements. So in the following array, I want to remove index 0 and its association, then I will implode.
[0] => Bikes, [1] => Hardtails, [2] => XC
I have the following code so far which looks good so far. However I'm struggling to finish it.
$cat_path = explode("->",$cat_path);
if(count($cat_path,1) > 2){
foreach($cat_path as $path){
$counter = count($cat_path,1);
$remove = $counter -2;
}
}
Is the best solution here to use a nested loop which unsets the unwanted indexes and their associations?
You can use array_slice()
if (is_array($cat_path) && count($cat_path) > 2) {
$cat_path = array_slice($cat_path, -2);
}

is it possible display multidemintional array in php using for loop

I have a multi-dimensional array like
Array
(
[0] => Array
(
[ename] => willy
[due_date] => 12:04:2011
[flag_code] => 0
)
[1] => Array
(
[Father] => Thomas
[due_date] => 13:04:2011
[flag_code] => 0
)
[2] => Array
(
[charges] => $49.00
)
)
i want to display values of array using php. but still fail. please any one help me to do this task....?
Since you're so adamant that this be accomplished using only for loops, I have to assume this is a homework question. Because of this, I'll point you to several PHP manual pages in the hopes that you'll review them and try to learn something for yourself:
Arrays
For Loops
Foreach Loops
Now, I'm going to break your actual question a few different questions:
Is it possible to display a multidimensional array using for loops?
Yes. It's entirely possible to use a for loop to iterate over a multidimensional array. You simply have to nest for loops inside for loops. i.e. you create a for loop to iterate over the outer array, then inside that loop you use another for loop to iterate over the inner array.
How can I iterate over a multidimensional array using a for loop?
Generally, when you use a for loop, the loop will look something like this:
for($i = 0; $i < $maxValue; $i++) {
// do something with $1
}
While this works well for indexed arrays (i.e. arrays with numeric keys), so long as they have sequential keys (i.e. keys which use each integer in order. for example, an array with keys 0, 1, and 2 is sequential; an array with keys 0, 2, and 3 is not because it jumps over 1), this doesn't work well for associative arrays (i.e arrays with text as keys - for example, $array = array("abc" = 123);) because these arrays won't have keys with the numerical indexes your for loop will produce.
Instead, you need to get a bit creative.
One way that you could do this is to use array_keys to get an indexed array of the keys your other array uses. For example, look at this simple, one-dimensional array:
$dinner = array(
"drink" => "water",
"meat" => "chicken",
"vegetable" => "corn"
);
This array has three elements, each with an associative key. We can get an indexed array of its keys using array_keys:
$keys = array_keys($dinner);
This will return the following:
Array
(
[0] => drink
[1] => meat
[2] => vegetable
)
Now, we can iterate over the keys, and use their values to access the associative keys in the original array:
for($i = 0; $i < count($keys); $i++) {
echo $dinner[$keys[$i]] . "";
}
As we iterate over this loop, the index $i will be set to hold each index of the $keys array. The associated element of this key will be the name of a key in the $dinner array. We then use this key name to access the $dinner array elements in order.
Alternatively, you could use a combination of the reset, current and next functions to iterate over the values in the array, for example:
for($element = current($dinner);
current($dinner) !== false;
$element = next($dinner)
) {
echo $element . "<br />";
}
In this loop, you initialize the $element variable to be the first element in the array using reset, which sets the array pointer to the first element, then returns that element. Next, we check the value of current($dinner) to ensure that there is a value to process. current() returns the value of the element the array pointer is currently set at, or false if there is no element there. Finally, at the end of the loop, we use next to set the array pointer ahead by one. next will return false when we try to read beyond the end of the array, but we ignore that and wait for current to notice that there is no current element to stop the loop.
Now, having written all of that, there really isn't any reason to do jump through all these hoops, since PHP has the built-in foreach construct which allows you to iterate over each of an arrays elements, regardless of key type:
foreach($dinner as $key => $value) {
echo "The element in key '" . $key . "' is '" . $value ."'. <br />";
}
This is why I'm assuming this is a homework assignment, since you would probably never have reason to jump through these hoops in a production environment. It is, however, good to know that such constructs exist. For example, if you could use any loop but a foreach, then it would be a lot simpler to just use a while loop than to try to bash a for loop into doing what you want:
reset($dinner);
while (list($key, $value) = each($dinner)) {
echo "The value of '" . $key . "' is '" . $value . "'.<br />";
}
In summary, to iterate over a multidimensional array with associative keys, you would need to nest loops inside each other as shown in the answer to the first question, using one of the loops shown in the answer to the second question to iterate over the associative key values. I'll leave the actual implementation as an exercise for the reader.
To print the values of a array, you can use the print_r function:
print_r($array);
This saves a for-loop.
Just use the handy function print_r
print_r($myarray);
If you don't want to use the print_r function, then for a true n-dimensional array solution:
function array_out($key, $value, $n) {
// Optional Indentation
for($i=0; $i < $n; $i++)
echo(" ");
if(!is_array($value)) {
echo($key . " => " . $value . "<br/>");
} else {
echo($key . " => <br/>");
foreach($value as $k => $v)
array_out($k, $v, $n+1);
}
}
array_out("MyArray", $myArray, 0);
Not sure if its possible to do with a for loop and mixed associative arrays, but foreach does work just fine.
If you have to do it with a for loop, you want the following:
$count = count($array)
for($i = 0; $i <= $count; $i++)
{
$count2=count($array[$i]);
for($j = 0; $j <= $count2; $j++)
{
print $array[$i][$j] . "<br/>";
}
}
foreach( $array as $row ) {
$values = array_values($row);
foreach( $values as $v ) {
echo "$v<br>";
}
}
Should output:
willy
12:04:2011
0
Thomas
13:04:2011
0
$49.00
This will actually be readable:
echo '<pre>';
print_r($myCoolArray);
echo '</pre>';
You would need to do it using something like assigning array_keys to an array, then using a for loop to go through that, etc...
But this is exactly why we have foreach - it would be quicker to write, read and run. Can you explain why it must be done with for?

Categories