#php #arrays #json #drupal-8
Вопрос:
У меня есть json в следующем формате, я хотел обновить свой код во время работы функции form_alter drupal. Я сначала считываю данные с помощью json_decode, а затем присваиваю обновленные значения объекту, но при обновлении файла и сохранении формат массива json изменился.
Цитата
{
"products": [
{
"lcia_id": 118,
"name": "MnS Plant Kitchen No Chicken Pieces ",
"composition": [
[
{
"lcia_id": 223, } ], [ { "lcia_id": 221, } ] }, { "lcia_id": 111, },
"ingredients": [
{ "lcia_id": 204, "name": "Wheat and Pea Protein",},{ "lcia_id": 111, }, { "lcia_id": 111,
},
}
это мой код
$fileData = file_get_contents($file);
if (!empty($fileData)) {
$data = json_decode($fileData, TRUE);
$ingredientData = $data['ingredients'];
// var_dump($data);
// die("in value");
for($x = 0; $x < count($ingredientData); $x ){
$type = $ingredientData[$x]['type'];
$lcia_id = $ingredientData[$x]['lcia_id'];
if (($type == 'Ingredient' amp;amp; $bundle == 'ingredients') amp;amp; ($lcia_id == $lciaId)){
$ingredientData[$x]['country'] = $form_state->getValue('field_country')[0]['value'];
$ingredientData[$x]['address'] = $form_state->getValue('field_p_address')[0]['value'];
$ingredientData[$x]['serving_size'] = $form_state->getValue('field_serving_size')[0]['value'];
$ingredientData[$x]['description'] = $form_state->getValue('field_description')[0]['value'];
}
else{
Drupal::messenger()->addMessage("Either bundle or LCIA type is different.", 'error');
print_r("Missmatch bundle or lcia type.");
}
if(file_put_contents($path, json_encode($data['ingredients']))) {
echo 'success'; die('success');
}
else {
Drupal::messenger()->addMessage("Data is not updated in LCIA file.", 'error');
echo 'There is some error'; die('error');
}
}
}
формат json изменен, код удаляет основную оболочку json,вот так
Цитата
{
"products": [
{
"lcia_id": 118,
"name": "MnS Plant Kitchen No Chicken Pieces ",
"composition": [
[
{
"lcia_id": 223, } ], [ { "lcia_id": 221, } ] }, { "lcia_id": 111, },
"ingredients": [
{ "lcia_id": 204, "name": "Wheat and Pea Protein",},{ "lcia_id": 111, }, { "lcia_id": 111,
},
}
I am not getting whats going on code?