如何在foreach循环中使用array_replace?

时间:2019-02-25 12:45:47

标签: arrays loops symfony search replace

colums_arr:

array:4 [▼
  0 => "id"
  1 => "name"
  2 => "productgroup"
  3 => "category"
]

字段:

    {#9767 ▼
  +"id": array:9 [▶]
  +"name": array:8 [▼
    "fieldName" => "name"
  ]
  +"productgroup": array:19 [▼
    "fieldName" => "productgroup"
    "mappedBy" => null
  ]
  +"category": array:19 [▼
    "fieldName" => "category"
    "mappedBy" => null
  ]
}

我想做的是,只要在元素的fields的mappingBy中存在,我都想向值添加name。因此,columns_arr应该看起来像这样:

array:4 [▼
  0 => "id"
  1 => "name"
  2 => "productgroup.name"
  3 => "category.name"
]

这是我的方法:

  foreach ($fields as $field) {
      $MappedBy = isset($field['mappedBy']);
        if($MappedBy != true){
          $class_field = $field['fieldName'];
          $key = array_search($field['fieldName'],$input);
          $replace=array($key=>$class_field.".name");
          $columns_arr = (array_replace($input,$replace));
      }
    }

问题是,我的结果现在是:

array:4 [▼
  0 => "id"
  1 => "name"
  2 => "productgroup"
  3 => "category.name"
]

为什么未将name添加到productgroup

2 个答案:

答案 0 :(得分:3)

我无法真正回答您的问题,尚不清楚您在做什么以及您的值来自何处。因此,我尝试重建您的数组,而这是我不使用array_search的结果:

<?php

$columns = array(0 => "id", 1 => "name", 2 => "productgroup", 3 => "category");

$fields = array("id" => 9, "name" => array("fieldName" => "name"), "productgroup" => array("fieldName" => "productgroup", "mappedBy" => null), "category" => array("fieldname" => "category", "mappedBy" => null));
foreach ($fields as $key => $field) {
    if($key !== "id" && $key !== "name"){
        if(!isset($field['mappedBy'])){
            foreach($columns as $ckey => $column){
                if($column === $key){
                    $columns[$ckey] = $column.".name";
                }
            }
        }
    }
}

var_dump($columns);

var_dump输出:

array(4) { [0]=> string(2) "id" [1]=> string(4) "name" [2]=> string(17) "productgroup.name" [3]=> string(13) "category.name" }

答案 1 :(得分:2)

foreach ($fields as $key => $field) {
    $MappedBy = isset($field['mappedBy']);
      if($MappedBy != true){
        $columns_arr[$key] = $field['fieldName'].".name";
    }
  }

您需要像这样覆盖数组的正确键。