In php, I need a function to return all keys in array of objects. For arrays and objects I need keys like parentkey->key
. If the key is again an array, then I need parentkey->key->key1
.
My code as below
$array=json_decode('{"client":"4","gateWay":"1","store":"store.shop.com",
"valid":"true","po":34535,"additionalPO":23423,"customerNotes":"",
"orderItems":[{"item":"123","quantity":10,"supplierLotNo":"",
"customsValue":"","customsDescription":"","hsCode":""},
{"item":"345","quantity":50}],
"shippingInfos":[{"address":{"city":"Chennai",
"country":"India","postalCode":"86715","state":"TN",
"streetAddress1":"6971 North Street","streetAddress2":null},
"contact":{"company":null,"email":"info@store.com","firstName":"test",
"lastName":"test","phoneNo":null},"ServiceId":"3","thirdPartyAccountNo":"",
"signatureConfirmation":false,"saturdayDelivery":false}]}',true);
function array_keys_multi(array $array,$headkey,$pkey){
$keys = array();$hkey='';$parentkey='';
foreach ($array as $key => $value) {
//echo $key;
if($headkey!='' && !is_integer($headkey)){
if(!is_integer($key)){
if (is_array($value) || is_object($value)) {
if($pkey!='')
$parentkey=$pkey."->".$key;
else
$parentkey=$key;
foreach($value as $kk=>$val){
foreach($val as $kk1=>$val1){
$keys[]=$parentkey."->".$kk1;
}
}
//$keys[]=$parentkey."->".$key;
}else{
$keys[] = $pkey."->".$key;
$hkey=$headkey."->".$key;
}
}
}
else{
if(!is_integer($key)){
if($pkey!='')
$parentkey=$pkey."->".$key;
else
$parentkey=$key;
if (is_array($value) || is_object($value)) {
if($pkey!='')
$parentkey=$pkey."->".$key;
else
$parentkey=$key;
foreach($value as $kk=>$val){
//print_r($val);echo "==========";
foreach($val as $kk1=>$val1){
$keys[]=$parentkey."->".$kk1;
}
}
$hkey=$key;
}else{
$keys[]=$key;
}
}
}
if (is_array($value) || is_object($value)) {
echo $key."-----".$hkey."<br>";
$keys = array_merge($keys, array_keys_multi($value,$hkey,$key));
}
}
return $keys;
}
$k=array_keys_multi($array,'','');
print_r($k);
I need output as an array with the following key paths (notice no numeric keys are retained):
[
"client",
"gateWay",
"store",
"valid",
"po",
"additionalPO",
"customerNotes",
"orderItems->item",
"orderItems->quantity",
"orderItems->supplierLotNo",
"orderItems->customsValue",
"orderItems->customsDescription",
"orderItems->hsCode",
"shippingInfos->address->city",
"shippingInfos->address->country",
"shippingInfos->address->postalCode",
"shippingInfos->address->state",
"shippingInfos->address->streetAddress1",
"shippingInfos->address->streetAddress2",
"shippingInfos->contact->company",
"shippingInfos->contact->email",
"shippingInfos->contact->firstName",
"shippingInfos->contact->lastName",
"shippingInfos->contact->phoneNo",
"shippingInfos->ServiceId",
"shippingInfos->thirdPartyAccountNo",
"shippingInfos->signatureConfirmation",
"shippingInfos->saturdayDelivery"
]
How can I achieve this?