0

I am building a phonebook application that will generate a list of extensions from our phone system. The phone system has two elements; "name" and "extension". I would like to separate the name into first name and last name. I have already done this with the following:

list($ln,$fn) = explode(' ',$contact[1],2);

The problem is, I would like to add $ln and $fn to the array that is formed from the database query. The reason for this is because I am creating a json from the array. I have tried the following, but it does not seem to add the fname and lname element to the array:

$contact_array = array();
while ($contact=mysql_fetch_array($QUERYresult))
{
 if(preg_match('/\s/',$contact[1]))
 {
  //$count++;
  $contact_array[] = $contact;
  list($ln,$fn) = explode(' ',$contact[1],2);
  $contact['fname'] = $fn;
  $contact['lname'] = $ln;
 }
 fwrite($myJSON, json_encode($contact_array));

The output of this array only returns the database query, which looks like this:

Array
(
    [0] => Array
        (
            [extension] => 1000
            [name] => Extension 1
        )

    [1] => Array
        (
            [extension] => 1001
            [name] => Extension 2
        )
    )
2
  • Please stop using the mysql_ DB library. It was discontinued and deprecated years ago, and removed entirely in PHP7, mostly due to security issues. Switch to using mysqli or PDO asap. Commented Sep 6, 2017 at 16:04
  • The value of $contact is added to $contact_array when you do $contact_array[] = $contact;. It's not added by reference. Commented Sep 6, 2017 at 16:12

1 Answer 1

1

The problem seems to be mainly that you're adding the values after you've already passed the original version of $contact into $contact_array. So the extra values you add aren't included in that. Try moving those lines to before you do $contact_array[] = $contact;:

if(preg_match('/\s/',$contact[1]))
{
  //$count++;
  list($ln,$fn) = explode(' ',$contact[1],2);
  $contact['fname'] = $fn;
  $contact['lname'] = $ln;
  $contact_array[] = $contact;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. This was my problem!
@Intrepid no problem. Please remember to mark the answer as accepted if it worked for you - thanks :-)

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.