0

I Want to convert object keys into array keys. For example my keys like data.row.key into ["data"]["row"]["key"];

I want to an array format ["data"]["row"]["key"]

Thanks in Advance

teeyo
  • 3,665
  • 3
  • 22
  • 37
Gopal
  • 111
  • 8
  • read there - http://php.net/en/get-object-vars – splash58 Oct 27 '17 at 15:17
  • Do you mean you literally have a single array key of `data.row.key`, which you want to expand out? – iainn Oct 27 '17 at 15:18
  • Thanks for yor comment i have received string "data.row.key" but i need to create a array ["data"]["row"]["key"] – Gopal Oct 27 '17 at 15:21
  • You mean something like this? [Convert PHP object to associative array](https://stackoverflow.com/questions/4345554/convert-php-object-to-associative-array) – tyb Oct 27 '17 at 15:37
  • you can check this https://stackoverflow.com/questions/35426793/parsing-a-string-with-recursive-parentheses – Ravinder Reddy Oct 27 '17 at 16:21

1 Answers1

1

I am not sure what you exactly want but if your intention is to convert string to array format use the below code.

$key = 'data.row.key';
// explode it
$key_array = explode('.',$key);
$array_key_format = '';
foreach($key_array as $key) {
    $array_key_format .= '["'.$key.'"]';
}

echo $array_key_format;

Out Put:

["data"]["row"]["key"]

The out put is only string, cannot be used as array.

Ravinder Reddy
  • 3,869
  • 1
  • 13
  • 22
  • *"make sure we have an array to work with"* -- what makes you think `$key_array` is not an array? – axiac Oct 27 '17 at 16:33
  • @axiac. my mistake, explode always returns an array. – Ravinder Reddy Oct 27 '17 at 16:39
  • Thanks Ravinder Reddy. I want to use as array. So kindly help me. Now am using this way. like to change another way/simple way $keys = array_map('strrev', explode(".", strrev($key))); $setArrKeys = []; foreach ($keys as $key => $value) { $setArrKey[0][$value] = $setArrKeys; if($key == 0) $resultArr[0] = $setArrKey[0]; else { $setValue = $resultArr[0]; $resultArr = []; $resultArr[0][$value] = $setValue; } } – Gopal Oct 28 '17 at 10:04