PHP how do i write a multi dimmensional array into file - php

I am trying to use files to hold an array for checkers
this is the array
$board = array(
array(0,0,0,0,0,0,0,0,0),
array(0,0,0,0,0,0,0,0,0),
array(0,0,0,0,0,0,0,0,0),
array(0,0,0,0,0,0,0,0,0),
array(0,0,0,0,0,0,0,0,0),
array(0,0,0,0,0,0,0,0,0),
array(0,0,0,0,0,0,0,0,0),
array(0,0,0,0,0,0,0,0,0),
array(0,0,0,0,0,0,0,0,0)
);
while also giving the values so that i can set the beginning of the board with the pieces placed in a predefined positions to start the game in then have them user input which location they want to move the pieces into
I already have this while loop
$row = 0;
print "<form>";
print "<table border = 1>";
while ($row < 8){ // Counts to 8. (from 0...7 = 8 times. 0 ... 8 = 9 times)
print "<tr>";
$row++;
$col = 0; // reset column to 0 each time printing one row.
while ($col < 8){
print "<td>";
if($Board[$row][$col] == 0)
{
$value=$row.$col;
print "<input type=\"checkbox\" name=\"box[]\" value=\"$value\">";
// Add \ before " otherwise it will treat as the end of the quote.
}
print "</td>";
$col++;
}
print "</tr>";
}
print "</table>";
print "</form>";
}

file_put_contents($f, serialize($board));
this will serialize your multidimensional array in a file.
To read it back, use
$board = unserialize(file_get_contents($f));

2 variants:
using serialize
#dump:
file_put_contents('file_name', serialize($board));
#restore:
$board=unserialize(file_get_contents('file_name'));
using JSON:
#dump:
file_put_contents('file_name', json_encode($board));
#restore:
$board=json_decode(file_get_contents('file_name'));
JSON variant works faster, but can dump only simple structures (strings, arrays, numbers). serialize can dump objects too but works slower and generate more output

why don't you serialize the array and store it as a string into the file. to get the array back, you can read the string from the file and un-serialize it. have a read here here

Why serialize and store ? Even you can directly print array to file
ob_start();
print_r( $yourArry);
$output = ob_get_clean();
file_put_contents( 'yourfilename.txt',$output );
See example here http://www.my-php-scripts.net/index.php/Array-Scripts/php-write-multidimensional-array-into-file-advanced-php.html

Related

How do i find the number of elemets in a 2 demensional array in PHP?

Is there a function which can be used to get the number of columns of a 2D array?
I've come to realize that count() function will display the number of rows inside the 2D array but am interested in getting the number of columns inside each array.
How can I use the count() function or any other function to get the number of elements inside an array contained inside another array.
Here is a sample of the code that am working with:
<?php
$people = array(
array("Rodrick","Java","PHP"),
array("Jane","Python","Javascript"),
array("Tom","Python","R"),
array("Wangari","Ruby","Kotlin"),
);
for($row = 0 ; $row < count($people) ; $row++){
echo "The Programmers ".$row;
echo "<ol>";
for($col = 0 ; $col < 3 ;$col++){
echo "<li>".$people[$row][$col]."</li>";
}
echo "</ol>";
}
You can get the size of the second dimension by:
$ncols = count($people[$row]);
Your code could be like this:
<?php
$people = array(
array("Rodrick","Java","PHP"),
array("Jane","Python","Javascript"),
array("Tom","Python","R"),
array("Wangari","Ruby","Kotlin"),
);
for($row = 0 ; $row < count($people) ; $row++){
echo "The Programmers ".$row;
echo "<ol>";
$ncols = count($people[$row]);
for($col = 0 ; $col < $ncols ; $col++){
echo "<li>".$people[$row][$col]."</li>";
}
echo "</ol>";
}
?>
Do you really need to know the size of nested array?
Here is solution with foreach used:
$people = array(
array("Rodrick","Java","PHP"),
array("Jane","Python","Javascript"),
array("Tom","Python","R"),
array("Wangari","Ruby","Kotlin"),
);
foreach($people as $human){
echo "<ol>";
foreach($human as $data){
echo "<li>".$data."</li>";
}
echo "</ol>";
}
The number of columns is determined here on the basis of the first line.
$numberOfColumns = count(reset($people));
The calculation can be used for numerical and also for associative arrays.

Array in While Loop PHP

I have a while loop that loops through line of text
while ($line_of_text = fgetcsv($file_processing, 4096)) {
In this while loop I assign variables to different parts of the array
IF($i > 0)
{
echo "</br>";
$account_type_id = $line_of_text[0];
echo "Account Type ID: " . $account_type_id. "<br>";
$account_number = $line_of_text[1];
echo "account_number = " . $account_number . "<br>";
This while loop loops through many lines. I am trying to find a way to say that
IF $account_type_id == 99 then add $account_number to an array. Then outside of the while loop print out the whole array of $account_numbers where $account_type_id == 99.
I have tried using print_r but it will only display the last array...
To add the element to an array, you can use array_push.
First you need to create the array (before the while loop):
$my_array = array();
Then, in the while loop, do this:
if ($account_type_id == 99) {
array_push($my_array, $account_number);
}
Then to display the array, either use print_ror var_dump. To make the array easier to read, you can also do this:
echo "<pre>".print_r($my_array, 1)."</pre>";
Rocket H had the answer in the comment he posted
inside of your loop
if($account_type_id == 99){
$account_numbers[] = $account_number;
}
After loop
print_r($account_numbers);

Put the value of for loop inside array

I am trying to reate an array that contains all the odd numbers between 1 to 20,000. I Use the var_dump() at the end to display the array values without using loops.
For some reason it won't work out.
here's my code so far:
$array_variable = array();
for($i=1; $i<=20000; $i++){
if($i%2 == 1){ // if the remainder after division `$i` by 2 is one{
print_r($array_variable[$i]); // if odd, echo it out and then echo newline for better readability;
}
}
var_dump($array_variable);
You need to push the values to your array first:
$array_variable = array();
for($i=1; $i<=20000; $i++){
if($i%2 == 1){
$array_variable[] = $i;// or array_push($array_variable, $i);
}
}
var_dump($array_variable);
Otherwise your array stays empty.
This results in alot of undefined indexes because you're not adding anything to $array_variable.
Change the code to this:
$array_variable = array();
for($i=1; $i<=20000; $i++){
if($i%2 == 1){ // if the remainder after division `$i` by 2 is one{
$array_variable[] = $i; // $array_variable[] means adding something to the array
}
}
var_dump($array_variable); //dump all odd numbers
For better readability of the array you could use:
echo "<pre>";
print_r($array_variable);
echo "</pre>";
Your $array_variable is empty because you never add any elements to it. Try this instead:
$array_variable = range(1, 20000, 2);
$array_variable = array();
for($i=1; $i<=20000; $i++){
if($i%2 == 1){ // if the remainder after division `$i` by 2 is one{
array_push($array_variable, $i); //Push the variable into array
}
}
var_dump($array_variable); //dump all odd numbers
You are trying to print an element it does not exist since the array is empty.
If you insist on using an array use this code, you notice you assign a value to the array elements: ( and also if you want to display it on a new line in browser, use echo commented out): (if interested about more: what is the difference between echo and print_r
<?php
$array_variable = array();
for($i=1; $i<=20000; $i++){
$array_variable[$i]=$i;//assignment
if($i%2 == 1){ // if the remainder after division `$i` by 2 is one{
print_r($array_variable[$i]); // if odd, echo it out and then echo newline for better readability;
//echo $array_variable[$i].'<br>';
}
}
var_dump($array_variable);
?>

Adding some data to an array

ok here is some code
$highestRow = 16; // e.g. 10
$highestColumn = 'F'; // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); // e.g. 5
for ($row = 9; $row <= $highestRow; ++$row) {
$val=array(); //i have initialized the array
for ($col = 1; $col <= $highestColumnIndex; ++$col) {
$cell=$objWorksheet->getCellByColumnAndRow($col, $row);
$val[]=$cell->getValue();
}
echo $val[0] //from what is read from excel, it returns data like this 7563
}
How the data was in the excel sheet before, B9 had 75, B10 had 6 and B11 had 3
After reading i echo $val[0] //output 7563
Now i would like to add additional data to the result so if i echo $val[0] after adding the info it shows the output as
echo $val[0] //output average=75% ; rsd = 6%; n=3% instead of just 7563
foreach ($k as $key=>$value) {
echo $key."=".$value."; ";
}
Depending on the type of array that you have you can either directly edit it as a string, or you have to turn it into a string.
If the value is already a string you can simply do string manipulation, you can create a temporary or use the original string and edit it all at once to be echoed, depends on what you prefer.
$strTemp = "output average=substr($var[0],0,2)% ; "rsd =substr($var[0]%,2,1); n=substr($var[0]%,3,1);" //can also use $var[0] instead of strTemp
If the values are in integer format you will have to turn the values into strings and then you can move on from there. If you don't know how, I advise this thread: Converting an integer to a string in PHP
Another thing, I'd advise storing the numbers in different parts of the array, that way its easier to reference them and tell them apart.

Trouble with adding to array in while loop

I have a while loop that uses the fgetcsv function and iterates through a csv file until the end. In the loop I want to add a value from a specific column to a new array.
Everything works as it echos the value from the column that I need. However when I put the line in to add to the array it does not work. I have a HTML table that prints after the PHP code however when I use the line to add to the array it does not work.
I have looked on the internet and everything I have seen is doing it the way I have done so I am a little confused.
Here is my code:
$amountRecords = 0;
$totalValue = 0;
$valueArray = array();
$handle = fopen('data.csv', 'r');
// to skip the header names/values
fgetcsv($handle);
while($row = fgetcsv($handle, "\r"))
{
$valueArray[$amountRecords] += $row[1]; // THIS IS THE LINE THAT IS NOT WORKING
$totalValue = $totalValue + $row[1];
$amountRecords++;
}
There is some strangeness with your code. You're incrementing $amountRecords each time, so you'll never access the same index in $valueArray twice, yet, you're adding values to each element. Possibly you simply mean to assign the value with $valueArray[$amountRecords] = $row[1]; instead of +=?
If that's the case, it looks like you're simply attempting to add the item onto the end of the array, extracting column 1 into its own array. You should use array_push or array[]= syntax for that:
while($row = fgetcsv($handle, "\r"))
{
// Add $row[1] to the end of $valueArray
$valueArray[] = $row[1];
$totalValue = $totalValue + $row[1];
}
The += operator is for adding something to an existing value. Typing a += b is the same as typing a = a + b. You should be using that operator on the next line, for example:
$totalValue += $row[1];
As a final suggestion, learn to do some basic debugging. If your loop isn't working, make it show you what it's doing during each iteration. Use var_dump to inspect your variables and make sure they actually contain what you think they contain. Using var_dump($row) would be especially useful in making sure that $row[1] is the correct index.
echo "Before loop\n";
while($row = fgetcsv($handle, "\r"))
{
echo '$row contains: ';
var_dump($row);
$valueArray[] += $row[1]; // THIS IS THE LINE THAT IS NOT WORKING
echo '$valueArray now contains ':
var_dump($valueArray);
$totalValue = $totalValue + $row[1];
}
echo "After loop\n";
From my understand of your script $valueArray[$amountRecords] += $row[1]; would not make any logical sense because its dependent on $amountRecords ++; which would always increase .
I think your script would work fine like this
while ( $row = fgetcsv($handle, "\r") ) {
$valueArray[] = $row[1]; // Put all Row[1] Into a array
$totalValue += $row[1]; // Sum total Value
$amountRecords ++; //Get Record Count
}

Categories