2

I'm currently working on a school project and can't manage to figure out how to implode and explode the array properly. My goal is to be able to add new users, be able to delete users, and update users. I need to get my key value pair correctly in order to achieve that.

Thank you

<?php
class index {

    function __construct(){}

My CSV read results is the following

Array
(
    [Email = [email protected]] => FirstName = fake_firstname
)
    public function display() {

        $filename   = 'testfile.csv';
        $lines      = file($filename);
        $data       = array();

        echo "<tr>
        <th>Email</th>
        <th>First</th>
        <th>Last</th>
        </tr><br>";
        foreach($lines as $info) {
            list($key, $value) = explode(',', $info);
            $result[$key] = $value;

            echo "<pre>";
            print_r($result);
            echo "</pre>";
        }
    }

    public function add($Fname, $Lname, $Email) {
        $this->Fname = $Fname;
        $this->Lname = $Lname;
        $this->Email = $Email;
        $this->person = array('Email'=>$this->Email,'FirstName' =>$this->Fname,
        'LastName' =>$this->Lname);
        $this->save($this->person);

        print_r($this->person);
    }

    public function save($arr) {
        $filename = 'testfile.csv';
        $myfile = fopen($filename, "a+") or die("Unable to open file!");
        foreach($arr as $key => $value){
            $new[] = $key.' = '.$value;
            $final =  implode(",", $new);
        }
        fwrite($myfile, $final."\r\n");

        fclose($myfile);
    }

My CSV saved results is the following Email = [email protected],FirstName = fake_firstname,LastName = fake_lastname

    public function form(){
        include('add.html');
    }

} // close off class index

?>
3
  • Why dont you get the content of the csv file as a string, use explode twice, one time with explode(",", $CSVString) and then for each index call another explode with explode("=", $array[$i]) and if it is needed trim() around the second explode to get rid of spaces at the end and beginning - If this does the trick I will put it up as an answer, if not let me know :) Commented Nov 7, 2015 at 15:40
  • I did the following and it saying that the second explode should be a string. foreach($lines as $info) { $CSVString = explode(',', $info); $last = explode('=', $CSVString); echo "<pre>"; print_r($last); echo "</pre>"; Commented Nov 7, 2015 at 16:01
  • see my answer below. I hope it helps you :) Commented Nov 7, 2015 at 16:17

4 Answers 4

1

Why dont you get the content of the csv file as a string, use explode twice, one time with explode(",", $CSVString) and then for each index call another explode with explode("=", $array[$i]) and if it is needed trim() around the second explode to get rid of spaces at the end and beginning. Note that the second explode is with an array, so you have to use

$email = trim(explode("=", $yourArray[0])[1]);
$Fname = trim(explode("=", $yourArray[1])[1]);
$Lname = trim(explode("=", $yourArray[2])[1]);

This very compact code creates three array, one for each information (mail, Fname, Lname) and directly picks the neccessary string, trims it and puts the value into a variable. If you need further help or explenation please let me know.

Sign up to request clarification or add additional context in comments.

3 Comments

Looking good so if i wanted to unset a particular user using the email as key, can i do a loop through the array and if the email == $email unset myarray?
I do not really get what you want to do... If your original question has been answerde I would appreciate an accept answer from you :) For your second question, please describe it further or create new one. If you do the second post the link here, then I can check it out as well.
Now i need to put an edit button next to the display. I managed to put a Href edit passing down $email, $firstname, and $lastname and receiving the post request on a edit function. Problem is that the edit info is being added to the bottom i need a way to replace the value with the new edit value and rewrite the array. Email First Last [email protected] test_firstname test_lastname Edit [email protected] test_firstname test_lastname Edit
1

Clearly you are in control of the structure of the .csv file. So I say, use the keys as headers in the .csv. personFile.csv should start with just the headers in it

personFile.csv

Email,First Name,Last Name

With ONLY that line in it

<?php
class index {

    function __construct(){}

    public function display() {
        $filename   = 'personFile.csv';
        $lines      = file($filename);
        $data       = array(); // store the contents of the file in an associative array for future use?

        // the first row is the header
        $headers = $lines[0];
        $countHeaders = count($headers); // store the count for future use
        echo "
        <tr>
            <th>" . implode("</th><th>",explode(",",$headers)) . "</th>
        </tr>";

        // array_slice($lines, 1) will return all the lines in $lines except for the first line
        foreach(array_slice($lines,1) as $row) {
            echo "
        <tr>
            <td>" . implode("</td><td>",explode(",",$row)) . "</td>
        </tr>";
        }
    }
    public function add($Fname, $Lname, $Email) {
        $this->Fname = $Fname;
        $this->Lname = $Lname;
        $this->Email = $Email;
        $this->person = array('Email'=>$this->Email,'FirstName' =>$this->Fname,
        'LastName' =>$this->Lname);
        $this->save($this->person);

        print_r($this->person);
    }

    public function save($arr) {
        $filename = 'personFile.csv';
        $myfile = fopen($filename, "a+") or die("Unable to open file!");

        $final = "\r\n" . implode(',',$arr);

        fwrite($myfile, $final);

        fclose($myfile);
    }
    public function form(){
        include('add.html');
    }
    //return true if the person was found and removed. else return false
    public function removePersonUsingEmail($emailToRemove) {
        $filename = 'personFile.csv';
        $lines      = file($filename);

        // the first row is the header
        $headers = $lines[0];
        $emailColumn = array_search("Email",$headers);

        $lines = array_slice($lines, 1);
        // array_slice($lines, 1) will return all the lines in $lines except for the first line
        foreach($lines as $rowNum => $row) {
            if($row[$emailColumn] === $emailToRemove) {
                unset($lines[$rowNum]);
                $final = implode(",",$headers);
                foreach($lines as $row) {
                    $final .= "\r\n" . implode(",",$row);
                }

                $myfile = fopen($filename, "w") or die("Unable to open file!");
                fwrite($myfile, $final);
                fclose($myfile);
                return true;
            }
        }

        return false;
    }
} // close off class index
?>

Comments

0

You could also explode each line once

<?php

$line = 'Email = [email protected],FirstName = fake_firstname,LastName = fake_lastname';

$parts = explode( ',', str_replace( array( ' = ', 'Email', 'FirstName', 'LastName'), '', $line ) );

// email = $parts[0]
// firstname = $parts[1]
// lastname = $parts[2]
?>

Comments

0
list($fname, $lname) = explode(' ', $N1,2);

Can anyone explain what does "2" denotes in this?

1 Comment

If you have new question please ask it stackoverflow.com/questions/ask. Don't post question in comments. Other wise it has been flag and get deleted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.