2
while ($selected_row = $stmt - > fetch(PDO::FETCH_ASSOC)) {
    $tmp_key = $selected_row['tin']; //adding a temp key
    //$tmp_key = $selected_row['tin']; //adding a temp key
    $new_data[$tmp_key]['tin'] = $selected_row['ownertin'];
    $new_data[$tmp_key]['lastname'] = $selected_row['ownerlastname'];
    $new_data[$tmp_key]['firstname'] = $selected_row['ownerfirstname'];
    $new_data[$tmp_key]['ownershipfrom'] = $selected_row['ownershipfrom'];
    $new_data[$tmp_key]['type'] = $selected_row['ownership'];
    $new_data[$tmp_key]['middleinitial'] = $selected_row['ownermiddlename'];
    $new_data[$tmp_key]['suffix'] = $selected_row['ownersuffix'];

    $sudky = (isset($new_data[$tmp_key]['Address'])) ? count($new_data[$tmp_key]['Address']) : 0; //getting the key for student child array

    $new_data[$tmp_key]['Address'][$sudky]['contactflag'] = $selected_row['contact_flag'];
    $new_data[$tmp_key]['Address'][$sudky]['tin'] = $selected_row['ownertin'];
    $new_data[$tmp_key]['Address'][$sudky]['mobile'] = $selected_row['mobile'];
    $new_data[$tmp_key]['Address'][$sudky]['landline'] = $selected_row['landline'];
    $new_data[$tmp_key]['Address'][$sudky]['email'] = $selected_row['email'];
    $new_data[$tmp_key]['Address'][$sudky]['province'] = $selected_row['addressprovince'];
    $new_data[$tmp_key]['Address'][$sudky]['municipality'] = $selected_row['addressmunicipality'];
    $new_data[$tmp_key]['Address'][$sudky]['barangay'] = $selected_row['addressbarangay'];
    $new_data[$tmp_key]['Address'][$sudky]['street'] = $selected_row['addressstreet'];
    $new_data[$tmp_key]['Address'][$sudky]['zipcode'] = $selected_row['addresszipcode'];

}
$new_data = array_values($new_data);
$input = array_map("unserialize", array_unique(array_map("serialize", $new_data)));
//print_r($new_data);
echo json_encode($new_data, JSON_UNESCAPED_UNICODE);

Is there a better way to create this multidimensional array without having the duplicate address

8
  • You can use PDO::* to fetch and return in a multidimensional array. Commented Sep 24, 2015 at 3:20
  • And can you edit and add your table structure? Commented Sep 24, 2015 at 3:36
  • how do you use pdo to do that i never done that before @EliasNicolas Commented Sep 25, 2015 at 5:53
  • See this php.net/manual/en/pdostatement.fetchall.php, It should fetch all at once, use the fetch_style flag to add PDO::FETCH_ASSOC|PDO::FETCH_GROUP and in MYSQL use Group by... Then you can do foreach() Commented Sep 25, 2015 at 6:15
  • i wont be able to test it right now but as soon as i can i will send a reply on this comment thank you for the idea Commented Sep 25, 2015 at 6:19

2 Answers 2

1

I prefer this structure of building the array because (at least to me) it's clearer what's where.

$new_data = array();
while($selected_row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $tmp_key = $selected_row['tin'];
    // don't write the same data over and over again
    if(!isset($newData[$tmp_key])) {
        $newData[$tmp_key] = array(
            'tin'           => $selected_row['ownertin'],
            'lastname'      => $selected_row['ownerlastname'],
            'firstname'     => $selected_row['ownerfirstname'],
            'ownershipfrom' => $selected_row['ownershipfrom'],
            'type'          => $selected_row['ownership'],
            'middleinitial' => $selected_row['ownermiddlename'],
            'suffix'        => $selected_row['ownersuffix'],
            'Address'       => array()
        );
    }
    $newData[$tmp_key]['Address'][$selected_row['contact_flag']] = array(
        'contactflag'  => $selected_row['contact_flag'],
        'tin'          => $selected_row['ownertin'],
        'mobile'       => $selected_row['mobile'],
        'landline'     => $selected_row['landline'],
        'email'        => $selected_row['email'],
        'province'     => $selected_row['addressprovince'],
        'municipality' => $selected_row['addressmunicipality'],
        'barangay'     => $selected_row['addressbarangay'],
        'street'       => $selected_row['addressstreet'],
        'zipcode'      => $selected_row['addresszipcode']
    );
}

Since your addresses are not duplicated, this should produce the desired array structure.

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

7 Comments

no i dont have duplicate data the result return is just duplicate
do i have to change anything in the code because i get [] in response from server also i have error in $newData[$tmp_key]['Address'][] => array( i had to change it to $newData[$tmp_key]['Address'][] = array(
what i did is change the new_data above to newData but then the result is just the same as my previous code the address has duplicate. but i did return the desired structure only there is again the duplicate
you know what i did a digging in your answers and i found this if(!isset($newData[$tmp_key]['Address'][$selected_row['ownertin']])) { $newData[$tmp_key]['Address'][$selected_row['ownertin']] = array( what i did is i change it to if(!isset($newData[$tmp_key]['Address'][$selected_row['ownertin']])) { $newData[$tmp_key]['Address'][$selected_row['contact_flag']] = array( since only 0 and 1 will the value i think i got it working ok. can you revert to that answer?also i will keep on testing is there will be another issue.
also i tried it like the answer only difference is i added $newData[$tmp_key]['Address'][$selected_row['contact_flag']] = array( seems to be ok what do you think? just add that to answer and if dont see any problem i will accept it thank you for the idea
|
0

In your case all the keynames are not intersect in two arrays, so I suggest to change the field names to the same as keys and make a different order, so later you can slice the result for two arrays.
The $selected_row must look like this:

$selected_row=[
    'tin_key'=>...
    'lastname'=>...
    'firstname'=>...
    'ownershipfrom'=>...
    'type'=>...
    'middleinitial'=>...
    'suffix'=>...
    'tin'=>... //this field will be reused in slices
    'contactflag'=>...
    'mobile'=>...
    'landline'=>...
    'email'=>...
    'province'=>...
    'municipality'=>...
    'barangay'=>...
    'street'=>...
    'zipcode'=>...
]

Now let's try to make your code smaller:

while ($selected_row = $stmt - > fetch(PDO::FETCH_ASSOC)) {
    $data = &$new_data[$selected_row['tin_key']]; // By reference assignments will go directly to array
    if(!$data) //Do not overwrite existing
        $data=array_slice($selected_row,1,7);

//Version from question
    $contact=&$data['Address'];
    $contact_tmp=array_slice($selected_row,7);
    if(!in_array($contact_tmp,$contact?:[]))
        $contact[]=$contact_tmp;

//Better version with some unique key as it was mentioned in answer above ex. 'contact_flag' or maybe 'tin' ?
    $contact=&$data['Address'][$selected_row['contact_flag']];
    if(!$contact)
        $contact=array_slice($selected_row,7);
}

//Good practice - clear pointer variables, or if you use them, 
//you'll corrupt last elements of array to where they were referencing in last loop.
unset($data,$contact);

Now you do not need find unique records after loop.
By the way, I prefer put assignments inside if() and reduce code by one line, ex.:

    if(!$contact=&$data['Address'][$selected_row['contact_flag']])

1 Comment

This one I don't like. Smaller doesn't necessarily mean better. Imagine yourself reading this code. WTF is array_slice($selected_row,7);? WTF is $contact=&$data['Address'];? Yes, it can be deciphered. Still it takes some effort, as opposed to reading a plain list of assignments and having a clear idea which column goes where.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.