0

I have a a loop that loops through data, what I am trying to achieve is for each loop an array is appended to another array before it is returned.

Here is what I have so far-

$response = array();
$response["CorrelationId"] = $correlationId;

This code sits outside the loop as I only want to return the "CorrelationId" once... This all works fine... for now I suppose!

foreach ($products as $value){
            $pid = mysql_escape_string($value['ProductId']);
            $dname = mysql_real_escape_string($value['departmentName']);
            $cname = mysql_real_escape_string($value['categoryName']);
            $pname = mysql_real_escape_string($value['productName']);

            //Insert Product data into DB
            $insert_product = "SQL Goes Here";
            $insert_result = mysql_query($insert_product);
            if(mysql_insert_id() >  0){
                $response["Messages"] = array("$pid Has been added.");
            }

        }
        return $response;

All that this is achieving so far is to add the last loop to the array. If I send 2 piecies of data to the loop, it will only have the last one in the array...

Am I missing something very basic here?

All I want if I where to send two pieces of data is to have the CorrelationId and 2 ["Messages"] returned.

Thanks

0

2 Answers 2

1

Change:


$response["Messages"] = "$pid Has been added.";
//To
$response["Messages"][] = "$pid Has been added.";

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

Comments

0

That's because you are overrriding $response["Messages"]. you should do (inside the loop)

 $response["Messages"][] ="$pid Has been added.";

and outside the loop

 $response["Messages"] = array();

1 Comment

It's always something blatantly obvious! Thanks I have been banging my head against a wall over this!

Your Answer

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