0

I'm trying to build an array that I can output using JSON. For whatever reason, it will only add one element to the array, even if there are multiple email addresses that come back with the object. I know this because the loop executes the correct amount of times. However the new values are not added to the array. I tried array_push but it mal forms the array and jQuery wont process it correctly.

        $load_model = $this->loadModel("LoadModel");
        $x = $load_model->updateLoad($LoadRate, $carrID, $comment, $temp, $loadStatus, $contactID, $load_id);
            if($x==true){
                $arr=array();
                foreach($load_model->loadEmailAddresses($load_id) as $val){
                   $arr['Email']= $val->Email;
                   $arr['ContactId']= $val->ContactId;
                }
                echo json_encode($arr);
            }

any ideas anyone?

2 Answers 2

4

You are setting the same element over and over in the loop. Every time it loops it will set $arr['Email'] and $arr['ContactId']. In the end you'll only ever get the last value that went through the loop. You'll need to create an array for the email and contact id, then add that array to $arr.

$load_model = $this->loadModel("LoadModel");
$x = $load_model->updateLoad($LoadRate, $carrID, $comment, $temp, $loadStatus, $contactID, $load_id);
    if($x==true){
        $arr=array();
        foreach($load_model->loadEmailAddresses($load_id) as $val){
           $arr[] = array('Email' => $val->Email, 'ContactId' => $val->ContactId);
        }
        echo json_encode($arr);
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Ah dhur, dunno how I missed that. Now I have a multidimensional array passed to the Jquery. Do I just iterate over the returned data?
Yup, you'll have to handle that data in jQuery knowing it could be any number of records.
1

You should change the lines in your foreach loop to

$arr[] = array(
    'Email'=>$val->Email,
    'ContactId'=>$val->ContactId,
);

Your array should grow properly at this point.

Comments

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.