具有完整父母的平面阵列(PHP,Symfony 3)

时间:2017-12-18 15:24:23

标签: php arrays json symfony multidimensional-array

对于使用Xing的社交媒体登录,我想验证从https://dev.xing.com/plugins/login_with/docs#signature-verification

中描述的XING发送的数据

我的页面将数据作为JSON-Array发送到PHP函数

public function indexAction(Request $request)
    {
       dump($request->request);
       $xingData=\GuzzleHttp\json_decode($request->request->get('xingData'),true);
       $xingUser=$xingData['user'];
       $xingError=$xingData['error'];
       $xingCookie=$request->request->get('xingCookie');
       $xingSerialised= $this->flatArray($xingUser);
       dump($xingUser);
       dump($xingError);
       dump($xingCookie);
       dump($xingSerialised);
       //$xingUserhash=hash_hmac('sha256',$xingSerialised,$this->container->getParameter('xing_salt'));
       //dump($xingUserhash);
        die(0);
        return $this->render('base.html.twig', array(
        ));
    }

function flatArray($fullArray = array())
{
    $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($fullArray));
    $elements = array();

    foreach($iterator as $element) {
        $elements[] = $iterator->key().$element;
    }

    return $elements;
}

JSON-decode-Function生成这个数组:

XingController.php on line 36:
array:9 [▼
  "id" => "MyId"
  "first_name" => "MyName"
  "last_name" => "MyLastName"
  "display_name" => "MyDisplayName"
  "active_email" => "my@email.de"
  "permalink" => "https://www.xing.com/profile/MyName"
  "business_address" => array:4 [▼
    "street" => "MyStreet"
    "city" => "MyCity"
    "province" => "MyProvince"
    "country" => "DE"
  ]
  "photo_urls" => array:1 [▼
    "maxi_thumb" => "https://www.xing.com/image/image.jpg"
  ]
  "professional_experience" => array:1 [▼
    "primary_company" => array:3 [▼
      "name" => "MyCompanyName"
      "title" => "Inhaber"
      "industry" => "CONSUMER_SERVICES"
    ]
  ]
]

问题是,我得到了

XingController.php on line 39:
array:14 [▼
  0 => "idMyId"
  1 => "first_nameMyName"
  2 => "last_nameMyLastName"
  3 => "display_nameMyDisplayName"
  4 => "active_emailmy@email.de"
  5 => "permalinkhttps://www.xing.com/profile/MyName"
  6 => "streetMyStreet"
  7 => "cityMyCity"
  8 => "provinceMyProvince"
  9 => "countryDE"
  10 => "maxi_thumbhttps://www.xing.com/image/image.jpg"
  11 => "nameMyCompanyName"
  12 => "titleInhaber"
  13 => "industryCONSUMER_SERVICES"
]

但我希望有完整的父母,例如:

 6 => "business_addressstreetMyStreet"

感谢您的任何想法/帮助!

1 个答案:

答案 0 :(得分:3)

尝试类似:

function flatArray($fullArray = array(), $parentkey=null)
    {
        $elements = array();

        foreach($fullArray as $key => $value) {
            if (is_array($value)) {
                $elements = array_merge($elements, $this->flatArray($value, $parentkey.$key));
            } else {
                $elements[] = sprintf('%s%s%s', $parentkey, $key, $value);
            }
        }

        return $elements;
    }

可能会提高递归

希望这个帮助

带完整递归的版本:

{{1}}