【问题标题】:how to use explode for an array of objects如何对对象数组使用爆炸
【发布时间】:2021-08-26 04:10:57
【问题描述】:

我有一个这样的数组:

array(5) {
["code"]=>
int(1)
["messageError"]=>
string(27) "La typologie est incorrecte"
["model"]=>
string(3) "lot"
["grp_regles"]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(3) {
["champ"]=>
string(21) "lot_surface_habitable"
["comparaison"]=>
string(7) "between"
["valeurAttendue"]=>
array(2) {
[0]=>
int(16)
[1]=>
int(40)
}
}
}
}
["prerequis"]=>
array(2) {
[0]=>
array(3) {
["champ"]=>
string(6) "typ_id"
["comparaison"]=>
string(1) "="
["valeurAttendue"]=>
int(1)
}
[1]=>
array(3) {
["champ"]=>
string(22) "tranche.fus.fup.fup_id"
["comparaison"]=>
string(1) "="
["valeurAttendue"]=>
int(1)
}
}
}

我想在“先决条件”中做一个 foreach:

$modelRetrieve = $this->retrieveModel($model);
        $modelFind = $modelRetrieve::find($id);
        $arrayError=[];
        $query = '';
        $path = storage_path() . "/json/controle.json";
        $json = file_get_contents($path);
        foreach (json_decode($json,true) as $key => $value) {
            $test = true;
            var_dump($value);
            if($value['model'] === $model ){
            foreach ($value['prerequis'] as $key => $value2) {
                if( $test && $modelFind[$value2['champ']] == (int)$value2["valeurAttendue"] ) 
                {
                    $test = true;
                }
            }
            }
        }

我需要在第二个 foreach 中使用 $value2['champ'],其中 $value2['champ'] 是“tranche.fus.fup_id。所以我需要分解它以获得 ['tranche']['fus']['fup_id']。 如何使用爆炸? 谢谢大家:)

【问题讨论】:

  • 当前你有:$value2['champ'] = "tranche.fus.fup.fup_id" 你需要:$value2['champ']['tranche']['fus'] ['fup']['fup_id'] = "" 对吗?
  • 我需要将 ['champ'] 替换为 ['tranche']['fus']['fup']['fup_id']。如果 champ 包含 '.',则获取 $value2['tranche']['fus']['fup']['fup_id'] 的值

标签: php arrays laravel explode


【解决方案1】:

要从结果的最里面的项开始嵌套字符串的$segments,我们必须将array_reverse()$segments 进行循环,然后将每个迭代的结果用另一个数组级别包装在下一次迭代,直到我们遍历整个 $segments 数组。

$exploded = array_reduce(array_reverse(explode('.', $value2['champ'])), function($res, $segment) {
    return [ $segment => $res ];
}, []);

【讨论】:

  • 请在您的答案中添加一些解释,以便其他人可以从中学习
【解决方案2】:

你可以使用 laravel data_get 助手:

data_get($value2, $value2['champ'])

【讨论】:

  • 哇,谢谢,太棒了!我不知道!
猜你喜欢
  • 2015-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多