从另一个数组动态检索数组并将其作为键值对推送到另一个关联数组

时间:2014-08-13 06:45:38

标签: php arrays associative-array array-push

我从api电话中得到了结果。

我将它存储在数组$phone_nums中。数组的结构如下:

结果:

    array (size=2)
      0 => 
        array (size=4)
          'is_error' => int 0
          'version' => int 3
          'count' => int 3
          'values' => 
            array (size=3)
              0 => 
                array (size=4)
                  "id"            ="1"
                  'contact_id'    = "207"
                  'phone'         = "8888888888"
                  'phone_id_type' = "2"
              1 => 
                array (size=4)

                  "id"            ="2"
                  'contact_id'    = "207"
                  'phone'         = "8475895894"
                  'phone_id_type' = "2"
              2 => 
                array (size=4)
                  "id"            ="2"
                  'contact_id'    = "207"
                  'phone'         = "48948594894"
                  'phone_id_type' = "2"

      1 => 
        array (size=5)
          'is_error' => int 0
          'version' => int 3
          'count' => int 1
          'id' => int 160
          'values' => 
            array (size=1)
              0 => 
                array (size=4)
                  "id"            ="1"
                  'contact_id'    = "207"
                  'phone'         = "48948594894"
                  'phone_id_type' = "2"

现在我必须从这个数组中获取电话号码,ph .no类型,然后添加一个新的关联数组$ ph_maps,其键为contact_id,并将相应的ph值映射到它。

$ ph_maps =(“207”=>数组(48782387489,4874843899,90483499908),208 =>数组(789732187,38983298,938938)

这是我的代码。它有一些问题。

for ($i=0; $i < count($phone_nums); $i++) { 
    for ($j=0; $j < $phone_nums[$i]['count']; $j++) {
        $ph_maps = array();
        $ph_maps[$phone_nums["values"][$i]["contact_id"]] = array($phone_nums[$i]['values'][$j]['phone']);
    }      

1 个答案:

答案 0 :(得分:1)

1 - 您每次使用$ph_maps = array();在循环中重置新数组,删除之前的条目。您当前的结果可能是具有单个contact_id / phone条目的数组。把它放在循环之外。

2 - 在第二个循环中,您没有为每个contact_id为数组添加新条目,而是设置一个新的唯一条目。您必须添加[]以强制创建新条目。

3 - 您为每个电话号码添加了一个新数组,而在您想要的输出中,您似乎只想要该值,因此您应该删除= array(...)

4 - 您的contact_id密钥不正确:使用$phone_nums[$i]["values"][$j]["contact_id"]代替$phone_nums["values"][$i]["contact_id"]

$ph_maps = array();
for ($i=0; $i < count($phone_nums); $i++) { 
    for ($j=0; $j < $phone_nums[$i]['count']; $j++) { 
        $ph_maps[$phone_nums[$i]["values"][$j]["contact_id"]][] = $phone_nums[$i]['values'][$j]['phone'];
    } 
}