I want to convert this array of string;
$arList = ["the","quick","brown","fox"];
into this format.
[
"the" => [
"quick" => [
"brown" => []
]
]
]
Sorry for not posting some code.
here is what I tried,
<?php
$arList = ["the","quick","brown","fox"];
$newList = [];
$pointer = $newList;
foreach($arList as $item) {
$pointer[$item] = [];
$pointer = &$newList[$item];
}
echo "<pre>";
print_r($newList);
echo "</pre>";
I found a solution from the net using the following code;
$result = array_reduce(array_reverse($arList), function($prevArray, $key){
return $prevArray ? [$key => $prevArray] : [$key];
}, null);
Related
I have a json data. Now I want to reform it. In my json data there is a property like person_on_zone I want to make a property named person_info and store them which person under this area.
Here is my data any code. Thanks in advance
My json data
$val = [
{
'city':'xx',
'zone':'yy',
'person_on_zone':'p1'
},
{
'city':'xx',
'zone':'yy',
'person_on_zone':'p2'
},
{
'city':'xx',
'zone':'yy',
'person_on_zone':'p3'
},
{
'city':'xx',
'zone':'ww',
'person_on_zone':'p1'
},
]
My expectation is
[
{
'city':'xx',
'zone':'yy',
'person_info':{
'person_on_zone':'p1',
'person_on_zone':'p2',
'person_on_zone':'p3',
}
},
{
'city':'xx',
'zone':'ww',
'person_info':{
'person_on_zone':'p1'
}
},
]
Here I tried
foreach ($val as $v) {
$new_array['city'] = $v['city'];
$new_array['zone'] = $v['zone'];
foreach ($val as $v2) {
$new_array['person_info'] = $v['person_on_zone'];
}
}
json_encode($new_array);
Try this, use $map to store key city-zone, then transform to array to get the result
<?php
$val = [
[
'city' => 'xx',
'zone' => 'yy',
'person_on_zone' => 'p1'
],
[
'city' => 'xx',
'zone' => 'yy',
'person_on_zone' => 'p2'
],
[
'city' => 'xx',
'zone' => 'yy',
'person_on_zone' => 'p3'
],
[
'city' => 'xx',
'zone' => 'ww',
'person_on_zone' => 'p1'
]
];
$map = [];
foreach ($val as $v) {
$key = $v['city'] . $v['zone'];
if (!isset($map[$key])) {
$map[$key] = [
'city' => $v['city'],
'zone' => $v['zone'],
'person_info' => []
];
}
$map[$key]['person_info'][] = $v['person_on_zone'];
}
print_r(array_values($map));
Correct Code
foreach ($val as $v){
$new_array['city'] = $v['city'];
$new_array['zone'] = $v['zone'];
foreach ($val as $v2){
$new_array['person_info'] = $v2['person_on_zone'];
}
}
json_encode($new_array);
try this:
first decode json array then use foreach loop with key
$val = json_decode($val);
foreach ($val as $v){
$new_array['city'] = $v->city;
$new_array['zone'] = $v->zone;
foreach ($val as $key=>$v2){
$new_array[$key]['person_info'] = $v->person_on_zone;
}
}
print_r($new_array);
I think you make a mistake around composing the json. I tried with your code and i found following is the correct way to do.. Remember single quote(') is not valid in json string that is being used to define key value pair in php
// I think your code has json string and i convert it into array of objects(stdClass)
// and if your code has array then keep you code intact but need to change the notation of
// objects to associative array.
// first thing first decode json string
$values = json_decode('[
{ "city":"xx",
"zone":"yy",
"person_on_zone":"p1"
},
{
"city":"xx",
"zone":"yy",
"person_on_zone":"p2"
},
{
"city":"xx",
"zone":"yy",
"person_on_zone":"p3"
},
{
"city":"xx",
"zone":"ww",
"person_on_zone":"p1"
}]');
// Now declare new values as array
$new_values = [];
// walk through each object
foreach ($values as $v){
// $v becomes an object of stdClass here
// $data is a temporary array
$data['city'] = $v->city;
$data['zone'] = $v->zone;
$data['person_info'] = [];
foreach ($values as $v2){
if(!in_array($data['person_info'],['person_on_zone' => $v2->person_on_zone]))
{
// compare if zones are same or not
if($v->zone == $v2->zone)
{
// push to the array instead of assiging
array_push($data['person_info'], ['person_on_zone' => $v2->person_on_zone]);
}
}
}
// make array unique
$data['person_info'] = array_map("unserialize", array_unique(array_map("serialize", $data['person_info'])));
array_push($new_values, $data);
}
// make array unique in mutidimensional array
$new_values = array_map("unserialize", array_unique(array_map("serialize", $new_values)));
echo '<pre>';
print_r($new_values);
echo '</pre>';
One simple foreach would do,
$result = [];
foreach ($arr as $key => $value) {
//created unique combination of city and zone as key
$result[$value['city'] . $value['zone']]['city'] = $value['city'];
$result[$value['city'] . $value['zone']]['zone'] = $value['zone'];
$result[$value['city'] . $value['zone']]['person_info'][] = ['person_on_zone' => $value['person_on_zone']];
}
echo json_encode(array_values($result));die;
array_values — Return all the values of an array
Working demo.
This seems simple, but has perplexed me. I need to get $env to look like $desired result.
I tried using explode and foreach loops in a multitude of ways but keep getting stuck.
$env = [
["mysql_user"=>"user var"],
["mysql_pass"=>"password var"],
["rabbit_list_one"=>"listone var"],
["rabbit_list_two"=>"listtwo var"],
["system_var_main_deep"=>"deep this"],
["system_var_main_that"=>"deep that"]
];
$desiredResult = [
"mysql" => [
"user" => "user var",
"pass" => "password var"
],
"rabbit" => [
"list" => [
"one" => "listone var",
"two" => "listtwo var"
]
],
"system" => [
"var" => [
"main" => [
"deep" => "deep this",
"that" => "deep that"
]
]
]
];
Double-check the formatting on $env, because you're showing arrays inside of the $env array rather than just key/value pairs. Assuming your input is correct, and there are actually inner arrays, this should work:
$out = [];
foreach ($env as $piece) {
foreach ($piece as $key => $value) {
$key_full = explode('_', $key);
$key_last = array_pop($key_full);
$pointer = &$out;
foreach ($key_full as $key_level) {
if (!isset($pointer[$key_level])) {
$pointer[$key_level] = [];
}
$pointer = &$pointer[$key_level];
}
$pointer[$key_last] = $value;
}
}
Based on Netrilix's answer, this was the final solution. This handled the situation where FOO_BAR_BAX and FOO_BAR were both set. We opted to always take the array over the string. Thank you all for all your help!
public function build() {
$config = $_ENV;
$out = [];
foreach ($config as $key => $value) {
$key_full = explode('_', $key);
$key_last = strtolower(array_pop($key_full));
$pointer = &$out;
foreach ($key_full as $key_level) {
$key_level = strtolower($key_level);
if (!isset($pointer[$key_level])) {
$pointer[$key_level] = [];
}
$pointer = &$pointer[$key_level];
}
$pointer = !is_array($pointer) ? [] : $pointer;
if (!isset($pointer[$key_last])) {
$pointer[$key_last] = $value;
}
}
return $out;
}
i had a array to each its item was object , i've converted that array with following code :
json_decode(json_encode($array), true)
that the result of code was a array like this :
[
'1'=>[
'slug'=>'a'
'title'=>'foo'
],
'2'=>[
'slug'=>'b'
'title'=>'bar'
],
'3'=>[
'slug'=>'c'
'title'=>'foo'
],
]
now i want to covert this array to somethings like this
[
'a'=>'foom',
'b'=>'bar',
'c'=>'foo',
]
how can i do it ??
Use foreach and array_combine()
foreach ($your_array as $key => $value) {
// get all the keys in $slug array
$slug[] = $value['slug'];
// get all the values in $title array
$title[] = $value['title'];
}
// finally combine and get your required array
$required_array = array_combine($slug, $title);
I think it can also be acheived with -
$requiredArray = array_combine(
array_column($your_array, 'slug'),
array_column($your_array, 'title')
);
You have to iterate over the initial array and create the new one like this:
$array = [
'1'=>[
'slug'=>'a'
'title'=>'foo'
],
'2'=>[
'slug'=>'b'
'title'=>'bar'
],
'3'=>[
'slug'=>'c'
'title'=>'foo'
],
];
$result = [];
foreach($array as $elem){
$index = $elem["slug"];
$value= $elem["title"];
$result[$index] = $value;
}
foreach($array as $elem){
$result[$elem["slug"]] = $elem["title"];
}
How to convert this array:
$array = [
"order" => [
"items" => [
"6" => [
"ndc" => "This value should not be blank."
],
"7" => [
"ndc" => "This value should not be blank."
]
]
]
];
to
$array = [
"order[items][6][ndc]" => "This value should not be blank.",
"order[items][7][ndc]" => "This value should not be blank.",
];
First array may have unlimited number of nested levels. So nested foreach is not an option.
I spent a lot of time searching for the solution and got nothing. Can, please, someone help or guide me?
Something like this should do the job :
$newArr = [];
function reduce_multi_arr($array, &$newArr, $keys = '') {
if (!is_array($array)) {
$newArr[$keys] = $array;
} else {
foreach ($array as $key => $val) {
if ($keys === '') $nextKey = $key; // first key
else $nextKey = '[' . $key . ']'; // next [keys]
reduce_multi_arr($val, $newArr, $keys . $nextKey);
}
}
}
reduce_multi_arr($array, $newArr);
print_r($newArr);
Output :
Array
(
[order[items][6][ndc]] => 'This value should not be blank.'
[order[items][7][ndc]] => 'This value should not be blank.'
)
in the below code, i used simple $key,$value but i want to use that code with associate array key. Then how can i do? Please help.
<?php
function custom_table_page_display() {
$jsonData = '{ "User":"John", "Age":22, "Country":"India" }';
$phpArray = json_decode($jsonData);
$rows = array();
foreach($phpArray as $key => $value)
{
$rows[] = $key;
$value1[]=$value;
}
$header=$rows;
$value11[]=$value1;
$output = theme('table',array('header'=>$header,'rows' => $value11));
return $output;
}
?>
You need to use
$phpArray = json_decode($jsonData, true);
The second argument says whether to return an associative array or object for a JSON object. By default it returns an object.
You can replace your foreach loop with:
$rows = array_keys($phpArray);
$value1 = array_values($phpArray);
For the data you gave in the comment below, you would do:
$rows = array_keys($phpArray['Class'][0]);
$values = array_map('array_values', $phpArray['Class']);
$values will then be a 2-dimensional array of values:
[ [ "John", 22, "India" ],
[ "Sam", 23, "Argentina" ],
[ "John", 22, "Algeria" ]
]
DEMO