问题
I am sending an array with other data using HttpClient
of angular 6.
And as it's mentioned in this post on github, sending arrays with HttpClient is still not available, so I had a problem reading arrays when received in PHP and var_dump
showed me null objects.
I found a solution by transforming the array into JSON
using json.stringify(array)
and it worked, as the received array is properly shown in var_dump
:
this.auth.saveUnitData(
unit_type,
location_id,
user,
number_of,
status,
add_date,
JSON.stringify(arrayOfActualities))
.subscribe(
(data)=>{
console.log(data);
},
(error)=>{
console.log(error);
}
)
var_dump()
result:
(
[unit_type] => 1
[location_id] => 1
[user] => 1
[number_of] => 2
[status] => Active
[add_date] => 2018-09-13
[arrayOfActualities] =>
[{"legalId":"","protectionId":"1","situationId":"","addDate":"2018-09-13"}]
)
In the PHP code and as sometimes a foreign key could be null as one of actualities sent through the array does not exist, I wrote the following script:
$arrayOfActualities = json_encode($arrayOfActualities);
if(sizeof($arrayOfActualities)>0)
{
foreach($arrayOfActualities as $array)
{
if($array['situationId']==="")
{
$situation_id=null;
}
else{
$situation_id = $array['situationId'];
}
if($array['legalId']==="")
{
$legal_id=null;
}
else{
$legal_id = $array['legalId'];
}
if($array['protectionId']==="")
{
$protection_id=null;
}
else{
$protection_id = $array['protectionId'];
}
$status = "Active";
try{
$sqlActualities = "INSERT into unit_situation_legal_protection(
unit_situation_legal_protection_status,
unit_situation_legal_protection_date_added,
legal_id, situation_id, protection_id, user_id)
VALUES(:actStatus, :dateAdded, :legal,
:situation, :protection, :userId)";
$sqlActExec = $this->conn->prepare($sqlActualities);
$sqlActExec->bindValue('actStatus', $status);
$sqlActExec->bindValue('dateAdded', $dateAdded);
$sqlActExec->bindValue('legal', $legal_id);
$sqlActExec->bindValue('situation', $situation_id);
$sqlActExec->bindValue('protection', $protection_id);
$sqlActExec->bindValue('userId', $user_id);
$sqlActExec->execute();
return "success";
}
catch(PDOException $e)
{
return $e->getMessage();
}
}
}
The problem is that nothing of the actualities are added to the database, and it's showing me the following error:
Warning: Invalid argument supplied for foreach()
So, if I changed to:
foreach(json_decode($arrayOfActualities) as $array)
I got the following error:
Invalid value of '['
I think this error because the array transformed into json and a [
was added before each row of the json, so php thought it's a value or something.
来源:https://stackoverflow.com/questions/52217106/angular-6-and-php-looping-over-json-array-sent-through-httpclient-giving-invalid