Related
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?
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);
?>
In my code I need to make a number of copies of a dummy array. The array is simple, for example $dummy = array('val'=> 0). I would like make N copies of this array and tack them on to the end of an existing array that has a similar structure. Obviously this could be done with a for loop but for readability, I'm wondering if there are any built in functions that would make this more verbose.
Here's the code I came up with using a for loop:
//example data, not real code
$existingArray = array([0] => array('val'=>2),[1] => array('val'=>3) );
$n = 2;
for($i=0;$i<$n;$i++) {
$dummy = array('val'=>0); //make a new array
$existingArray[] = $dummy; //add it to the end of $existingArray
}
To reiterate, I'd like to rewrite this with functions if such functions exist. Something along the lines of this (obviously these are not real functions):
//make $n copies of the array
$newvals = clone(array('val'=>0), $n);
//tack the new arrays on the end of the existing array
append($newvals, $existingArray)
I think you're looking for array_fill:
array array_fill ( int $start_index , int $num , mixed $value )
Fills an array with num entries of the value of the value parameter, keys starting at the start_index parameter.
So:
$newElements = array_fill(0, $n, Array('val' => 0));
You do still have to handle the appending of $newElements to $existingArray yourself, probably with array_merge:
array array_merge ( array $array1 [, array $... ] )
Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.
So:
$existingArray = array_merge($existingArray, $newElements);
This all works because your top-level arrays are numerically-indexed.
I have the following array:
$array = array(1,0,0,0,1,1,1,1,0,1,1,1,1,0,1,1,0,1,0,0,1,0,1);
I want split it up into individual arrays so that each array contains seven or less values.
So for example the first array will become:
$one = array(1,0,0,0,1,1,1)
$two = array(1,0,1,1,1,1,0)
$three = array(1,1,0,1,0,0,1);
$four = array(0,1);
Also how would you count the number of times 1 occurs in array one?
array_chunk() is what you are looking for.
$splitted = array_chunk($array, 7);
For counting the occurences I would be lazy. If your arrays only contain 1s or 0s, then a simple array_sum() would do:
print array_sum($splitted[0]); // for the first chunk
I want split it up into individual arrays so that each array contains seven or less values.
Use array_chunk(), which is made expressly for this purpose.
Also how would you count the number of times 1 occurs in array one?
Use array_count_values().
$one = array(1,0,0,0,1,1,1);
$one_counts = array_count_values($one);
print_r($one_counts);
// prints
Array
(
[0] => 3
[1] => 4
)
Assuming you want to preserve the contents of the array, I'd use array_slice() to extract the needed number of elements from the array, incrementing the '$offset' by the required count each time until the array was exhausted.
And as to your second question, try:
$num_ones=count(preg_grep(/^1$/,$array));
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?