为了账号安全,请及时绑定邮箱和手机立即绑定

如何在php中推送多维数组中的值

如何在php中推送多维数组中的值

PHP
慕标琳琳 2021-11-05 10:34:33
$classType 数组我正在存储类明智的类型,例如具有类型 A 的类 1 和具有类型的类 2 是 A 和具有类型的类 3 是 B$clollege['studentDetails']数组我想根据类从$classType数组中推送类型是什么类型$clollege['studentDetails']年级和$classType班级都是一样的。预期产出Array(    [0] => Array        (            [grade] => 2            [hobbies] => Array                (                    [0] => A                    [1] => B                )        [type] => A        )    [1] => Array        (            [grade] => 2            [hobbies] => Array                (                    [0] => A                )           [type] => A        )    [2] => Array        (            [grade] => 3            [hobbies] => Array                (                    [0] => C                )        [type] => A        )我已经尝试过但没有达到我预期的答案,请任何人更新我的答案,我已经在下面的部分中发布了我的代码。我知道这是一个简单的问题,如果有人发布你的,以便我可以从这里学习如何推动我的代码<?php$classType = [    ["class" => "1", "type" => "A"],    ["class" => "2", "type" => "A"],    ["class" => "3", "type" => "B"]];$clollege['studentDetails'] = [   ["grade" => "2", "hobbies" => ["A" , "B"] ],   ["grade" => "2", "hobbies" => ["A" ] ],   ["grade" => "3", "hobbies" => [ "C" ] ]];foreach ($classType as $item) {        $clollege['studentDetails'][$item['class']]['type'] = $item['type'];}echo "<pre>";print_r($clollege['studentDetails']);exit;?>更新代码部分$studentList['studentDetails'] = [    [ "group" => ["id" => 1 , "grade" => "2"] ],    [ "group" => ["id" => 2 , "grade" => "2", ] ],    [ "group" => [ "id" => 3, "grade" => "3"] ]];
查看完整描述

2 回答

?
holdtom

TA贡献1805条经验 获得超10个赞

您可以在array_walk()的帮助下尝试以下方法。


$classType = [

    ["class" => "1", "type" => "A"],

    ["class" => "2", "type" => "A"],

    ["class" => "3", "type" => "B"]

];


$clollege['studentDetails'] = [

    ["grade" => "2", "hobbies" => ["A" , "B"] ],

    ["grade" => "2", "hobbies" => ["A" ] ],

    ["grade" => "3", "hobbies" => [ "C" ] ]

];


$classType = array_column($classType, 'type', "class");

array_walk($clollege['studentDetails'], function(&$item) use($classType) {

    $item['type'] = $classType[$item['grade']];

});


echo '<pre>';

print_r($clollege['studentDetails']);

echo '</pre>';



查看完整回答
反对 回复 2021-11-05
?
呼唤远方

TA贡献1856条经验 获得超11个赞

您不能grade在单个或子数组元素中用作键 2 次,我已经通过使用type索引提到了解决方案。


你可以用foreach与array_reduce


 foreach($clollege['studentDetails'] as $key => &$val){

    $grade       = $val['grade'];

    $val['type'] = array_reduce($classType, function($r, $item) use ($grade){

      return ($item['class'] == $grade) ? $item['type'] : $r;

    }); 

  }

  print_r($clollege);

更新


更改代码


$grade = $val['grade'];


$grade = $val['group']['grade'];

如果有机会为这两种情况使用


$grade  = isset($val['group']['grade']) ? $val['group']['grade'] : $val['grade'];

工作演示:https : //3v4l.org/5HGLk


查看完整回答
反对 回复 2021-11-05
  • 2 回答
  • 0 关注
  • 136 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信