简体   繁体   English

无法从多维数组中获取字符串以写入PHP(Laravel 5.2)中的JSON文件-只是空引号

[英]Can't get a String from an Multi-Dimensional Array to write to a JSON file in PHP (Laravel 5.2) - just empty quotes

I have a multi-dimensional array which is from decoded JSON. 我有一个多维数组,它来自解码的JSON。 I can move through the array and echo out each element perfectly fine. 我可以遍历数组,并很好地回显每个元素。

However I cannot get my Array element to over write an element in the JSON file. 但是,我无法让我的Array元素在JSON文件中覆盖一个元素。

The interesting thing is that I can echo it out, it is of type string and I can write a hard-coded string between "quotes" to the JSON file. 有趣的是,我可以将其回显为字符串类型,并且可以在“引号”之间将硬编码的字符串写入JSON文件。

When I try to write to the file the existing JSON value is deleted and left as a pair of blank quotes "". 当我尝试写入文件时,现有的JSON值将被删除并保留为一对空白引号“”。 Not the whole file. 不是整个文件。 Just the exact element I'm targeting. 正是我要定位的元素。

I'm thinking it might have to do with scope of the arrays? 我在想这可能与数组的范围有关?

        foreach($data['Main'] as $sceneItem){
      $count = 0;
      //iterate over each element in every sceneItem looking for a matching field
      if(isset($sceneItem['Values'])){
        if(in_array($sceneItem['Values'], $template_fields)){
          //dd($user_input[$sceneItem['Values']]); //outputs desired string I'd like to put in JSON

          $data['Main'][$count]['Values'] = $user_input[$sceneItem['Values']];
          $count++;

       }
      }
    }

Sample of JSON: JSON样本:

{
 "Header": {
  "Project": "SchhhhriptTitle.aep"
 },
 "Main": [
  {
   "Title": "Text",
   "Comp": "Scene 1 - Introduction",
   "CompID": 40,
   "Name": "Company name ",
   "Layer": 1,
   "Values": "sc1txt2",
   "Font": "basictitlefont",
   "FontSize": 154,
   "FillColor": [
    0.95686000585556,
    0.95686000585556,
    0.95686000585556
   ]
  },
  {
   "Title": "Text",
   "Comp": "Scene 1 - Introduction",
   "CompID": 40,
   "Name": "Introducing",
   "Layer": 3,
   "Values": "sc1txt1",
   "Font": "basictitlefont",
   "FontSize": 154,
   "FillColor": [
    0.95686000585556,
    0.95686000585556,
    0.95686000585556
   ]
  },

I think you should use the php foreach using a reference , as in: 我认为您应该使用带有参考的php foreach ,例如:

foreach($data['Main'] as &$sceneItem){

that way you don't need to have the $count variable at all (which you reset at every iteration, not just at the beginning). 这样,您根本不需要$ count变量(您可以在每次迭代中重置,而不仅仅是在开始时重置)。 Doing that, instead of: 这样做,而不是:

$data['Main'][$count]['Values'] = $user_input[$sceneItem['Values']];

you can have 你可以有

$sceneItem['Values'] = $user_input[$sceneItem['Values']];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM