从多维数组PHP中获取元素

时间:2018-01-22 18:01:55

标签: php arrays multidimensional-array

使用下面的代码我试图获取每个键的数组,每个键都在for循环中,但最后数组结果是错误的。返回的DataIds是从所有数组合并的,我想从单个数组中获取元素。不确定如何在PHP中使用上面的代码?需要帮忙?对于每个循环,我希望将id附加到该特定键。

$student = [ABC, DEF];

public function getData()
{


     $newData = $newDataId = $newDataStudIds = $DataIds = [];
        foreach ($student as $key => $value) {

            $Ids   = [69, 70 ,71];

            //for above Ids foreach is executed
            foreach ($Ids as $Id) {

                $data = $this->api->request('marks', [
                    'Id'          => $Id,
                    'teacherId'   => 1
                ]);

                if ($data != 'error') {

                    $body = json_decode($data->getBody(), true);

                    foreach ($body['student'] as $student) {
                        $newData[$body['profile']['stud_id']][]   = $student['stud_id'];
                        /* so $newData will contain
                        array(69 => array('0'=>1,'1'=>"2"),
                             70 => array('0'=>2,'1'=>"3"),
                             71 => array('0'=>3,'1'=>"1")
                        )*/
                    }
                }
            }

            $newDataId = array_keys($newData);
            $newDataStudIds = array_values($newData);

            $DataIds = $this->implodeAllArray(',', $newDataStudIds);
            $DataIds = implode(',',array_unique(explode(',', $DataIds)));
            /*
                i want $DataIds = [69] => [1 ,2]
                [70] => [2, 3]
                [71] => [3, 1]

            But this $DataIds return array like 
            [69] => [1, 2 ,2 ,3]
            [70]  => [1, 2 ,2 ,3]
            [71]  => [1, 2 ,2 ,3]
            */

        }

}

public function implodeAllArray($glue, $arr){           
    for ($i=0; $i<count($arr); $i++) {
        if (@is_array($arr[$i])) 
            $arr[$i] = $this->implodeAllArray($glue, $arr[$i]);
    }            
    return implode($glue, $arr);
}

i want $DataIds = 

    [69] => [1 ,2]
    [70] => [2, 3]
    [71] => [3, 1]

 But this $DataIds return array like 
    [69] => [1, 2 ,2 ,3]
    [70]  => [1, 2 ,2 ,3]
    [71]  => [1, 2 ,2 ,3]

1 个答案:

答案 0 :(得分:0)

根据我对您的问题的解释,您可以转换:

$newData=array(69 => array('0'=>1,'1'=>"2"),
               70 => array('0'=>2,'1'=>"3"),
               71 => array('0'=>3,'1'=>"1"));

收件人($DataIds):

array(69 => array(1,2),
      70 => array(2,3),
      71 => array(3,1),
)

使用:

$DataIds=array_map(function($v){return [$v[0],(int)$v[1]];},$newData);
var_export($DataIds);

我正在有效地将所有字符串(键和值)转换为整数。 Demo