How to write the array keys into a string?

Hello, please help to write code.


I have the array:
$arr = ['Array' =>
[
 'purchases' => 'Purchase',
 'food' => 'Food',
 'vegetables' => 'Vegetables',
 'carrot' => 'Carrot',
]
];

print_r($arr)
[Array] => Array
(
 [purchases] => Buy
 [food] => Food
 [vegetables] => Vegetables
 [carrot] => Carrot
 )


Example - how should the result happen.
Want a new array like the following:
$arr = ['Array' => 
[
 'purchases' =>
[
 'name' => 'Purchase',
 'uri' => 'purchases'
],
 'food' =>
[
 'name' => 'Food',
 'uri' => 'purchases/food'
],
 'vegetables' =>
[
 'name' => 'Vegetables',
 'uri' => 'purchases/food/vegetables'
],
 'carrot' =>
[
 'name' => 'Carrot',
 'uri' => 'purchases/food/vegetables/carrot'
]
]
];

print_r($new_arr)
[Array] => Array
(
 [purchases] => Array
(
 [name] => Purchase
 [uri] => purchases
)

 [food] => Array
(
 [name] => Food
 [uri] => purchases/food
)

 [vegetables] => Array
(
 [name] => Vegetables
 [uri] => purchases/food/vegetables
)

 [carrot] => Array
(
 [name] => Carrot
 [uri] => purchases/food/vegetables/carrot
)

 )


Assume that you need to use foreach or for (If You decide to help, please do NOT write a new function).

June 10th 19 at 14:26
1 answer
June 10th 19 at 14:28
Solution
If primitive and not delve into the details:

<?php

$arr = ['Array' =-->
[
 'purchases' => 'Purchase',
 'food' => 'Food',
 'vegetables' => 'Vegetables',
 'carrot' => 'Carrot',
]
];


$newArr = [];
$prevUri = "";
foreach ( $arr['Array'] as $key => $name ) {
 $uri = $prevUri ? "{$prevUri}/{$key}" : $key;
 $newArr['Array'][$key] = [
 'name' => $name,
 'uri' => $uri,
];
 $prevUri = $uri;
}

print_r($newArr);


The result:
Array
(
 [Array] => Array
(
 [purchases] => Array
(
 [name] => Purchase
 [uri] => purchases
)

 [food] => Array
(
 [name] => Food
 [uri] => purchases/food
)

 [vegetables] => Array
(
 [name] => Vegetables
 [uri] => purchases/food/vegetables
)

 [carrot] => Array
(
 [name] => Carrot
 [uri] => purchases/food/vegetables/carrot
)

)

)
Thank You, very helpful! - kyra.Jenki commented on June 10th 19 at 14:31

Find more questions by tags ArraysPHP