$array['a:b']['c:d'] = 'test';
$array['a:b']['e:f']= 'abc';
I need output like below. array can have multiple level . Its comes with api so we do not know where colon come.
$array['ab']['cd'] = 'test';
$array['ab']['ef']= 'abc';
(untested code) but the idea should be correct if want to remove ':' from keys:
function clean_keys(&$array)
{
// it's bad to modify the array being iterated on, so we do this in 2 steps:
// find the affected keys first
// then move then in a second loop
$to_move = array();
forach($array as $key => $value) {
if (strpos($key, ':') >= 0) {
$target_key = str_replace(':','', $key);
if (array_key_exists($target_key, $array)) {
throw new Exception('Key conflict detected: ' . $key . ' -> ' . $target_key);
}
array_push($to_move, array(
"old_key" => $key,
"new_key" => $target_key
));
}
// recursive descent
if (is_array($value)) {
clean_keys($array[$key]);
}
}
foreach($to_move as $map) {
$array[$map["new_key"]] = $array[$map["old_key"]];
unset($array[$map["old_key"]]);
}
}
try this:
$array=array();
$array[str_replace(':','','a:b')][str_replace(':','','c:d')]="test";
print_r($array);
This seems like the simplest and most performant approach:
foreach ($array as $key => $val) {
$newArray[str_replace($search, $replace, $key)] = $val;
}
Related
I have a multi-dimensional array with key value pairs. Some of the values of the keys are arrays, and some of the values in that array are arrays as well. It is only 3 branches deep (for now), but I am trying to recursively loop through the array, save the key for each level of the branch, and create a new array when it reaches a string that also mimics the structure of the original array. When it reaches a string, there should be a new object instantiation for each value.
The code below sort of does this, but only creates a flat array.
foreach ($data as $key => $value) {
if (!is_array($value)) {
$a_objects[$key] = new Component([$key], $value);
} else {
foreach ($value as $valueKey => $valueValue) {
if (!is_array($valueValue)) {
$a_objects[$key . "_" . $valueKey] = new Component([$key, $valueKey], $valueValue);
} else {
foreach ($valueValue as $k => $v) {
$a_objects[$key . "_" . $valueKey . "_" . $k] = new Component([$key, $valueKey, $k], $v);
}
}
}
}
Here is my own best attempt at this but it does not seem to save into the b_objects after some testing it does not seem to be saving the object instances.
$b_objects = [];
function create_r($data, $id)
{
foreach ($data as $key => $value) {
if (is_array($value) == true) {
array_push($id, $key);
create_r($value, $id);
} else {
array_push($id, $key);
$b_objects[$key] = new Component($id, $value);
$id = [];
}
}
}
$id = [];
create_r($data, $id);
echo "this is b_objects";
echo "<pre>";
print_r($b_objects);
echo "</pre>";
I verified that $id array contains the right "keys". I feel like this solution is pretty close but I have no idea how to use my $id array to mimic the structure of the $data.
I want to be able to say $b_objects[$level1key][$level2key][$level3key]...[$leveln-1key] = new Component...
Thanks!
I suggest you pass $b_objects by reference to your create_r() function. Otherwise each function call will instantiate a new $b_objects variable which is not used anywhere in the code afterwards.
Passing by reference allows the function to actually change the input array. Notice the & sign in the function declaration.
function create_r($data, $id, &$res)
{
foreach ($data as $key => $value) {
if (is_array($value) == true) {
array_push($id, $key);
create_r($value, $id, $res);
} else {
array_push($id, $key);
$res[$key] = new Component($id, $value);
$id = [];
}
}
}
$id = [];
$b_objects = [];
create_r($data, $id, $b_objects);
I have an array like this:
$aMyArray = array(
"bmw"=>"user1",
"audi"=>"user2",
"mercedes"=>"user3"
);
And I only want to show the first two elements bmw=>user1 and audi=>user2.
But I want it by using a foreach loop.
If you want the first 2 by name:
Using in_array (documentation) is what you looking for:
$aMyArray = array("bmw"=>"user1", "audi"=>"user2", "mercedes"=>"user3");
$valuesToPrint = array("bmw", "audi");
foreach($aMyArray as $key => $val) {
if (in_array($key, $valuesToPrint))
echo "Found: $key => $val" . PHP_EOL;
}
If you want the first 2 by index use:
init index at 0 and increment in each iteration as:
$aMyArray = array("bmw"=>"user1", "audi"=>"user2", "mercedes"=>"user3");
$i = 0;
foreach($aMyArray as $key => $val) {
echo "Found: $key => $val" . PHP_EOL;
if (++$i > 1)
break;
}
$counter = 1;
$max = 2;
foreach ($aMyArray as $key => $value) {
echo $key, "=>", $value;
$counter++;
if ($counter === $max) {
break;
}
}
It is important to break execution to avoid arrays of any size looping until the end for no reason.
<?php
$aMyArray = array(
"bmw"=>"user1",
"audi"=>"user2",
"mercedes"=>"user3"
);
reset($aMyArray);
echo key($aMyArray).' = '.current($aMyArray)."\n";
next($aMyArray);
echo key($aMyArray).' = '.current($aMyArray)."\n";
Easiest way:
$aMyArray=array("bmw"=>"user1","audi"=>"user2","mercedes"=>"user3");
$i=0;
foreach ($aMyArray as $key => $value) {
if($i<2)
{
echo $key . 'and' . $value;
}
$i++;
}
I know you're asking how to do it in a foreach, but another option is using array travelling functions current and next.
$aMyArray = array(
"bmw"=>"user1",
"audi"=>"user2",
"mercedes"=>"user3"
);
$keys = array_keys($aMyArray);
//current($array) will return the value of the current record in the array. At this point that will be the first record
$first = sprintf('%s - %s', current($keys), current($aMyArray)); //bmw - user1
//move the pointer to the next record in both $keys and $aMyArray
next($aMyArray);
next($keys);
//current($array) will now return the contents of the second element.
$second = sprintf('%s - %s', current($keys), current($aMyArray)); //audi - user2
You are looking for something like this
$aMyArray = array(
"bmw"=>"user1",
"audi"=>"user2",
"mercedes"=>"user3"
);
foreach($aMyArray as $k=>$v){
echo $v;
if($k=='audi'){
break;
}
}
I'm trying to build a tree-map from categories.
I have the categories (I have a lot of categories and I want to remove duplicates and show them in a tree-map view)
$cat = array(
"Sneakers/Men",
"Sneakers/Women",
"Accessories/Jewellery/Men",
"Accessories/Jewellery/Women",
"Accessories/Jewellery/Men
");
...and I want them like this
$categories = array(
"Sneakers" => array(
"Men" => array(),
"Women" => array()
),
"Accessories" => array(
"Jewellery" => array(
"Men" => array(),
"Women" => array()
)
)
);
to print them like this
- Sneakers
-- Men
-- Women
- Accessories
-- Jewellery
--- Men
--- Women
Try this:
<?php
$cat = array(
"Sneakers/Men",
"Sneakers/Women",
"Accessories/Jewellery/Men",
"Accessories/Jewellery/Women",
"Accessories/Jewellery/Men
");
function buildTree($categories, $result = []){
$temp = [];
foreach($categories as $categoryString){
$catParts = explode('/',$categoryString);
if(count($catParts) > 1){
$temp[$catParts[0]][] = str_replace($catParts[0].'/','',$categoryString);
} else {
$temp[$catParts[0]] = [];
}
}
foreach($temp as $elemName => $elemVal){
$result[$elemName] = buildTree($elemVal);
}
return $result;
}
var_dump(buildTree($cat));
The most simple way is to use references, like this:
$out = [];
foreach ($cat as $str) {
$lookup =& $out;
foreach (explode("/", $str) as $part) {
$lookup =& $lookup[$part];
if (!isset($lookup)) {
$lookup = [];
}
}
}
$lookup initially refers to the whole expected result, then the reference is extended at each step to follow the path of nested members.
Note that each new member added looks like member-name => [], so that actually even final leaves are arrays: it may seem a bit weird, but is a pretty way to have a reduced code (each member is always ready to receive children).
And it's not a difficulty, though, to use the resulting array to then print it like the OP asked:
function nest_print($src, $level = 0) {
$prefix = '<br />' . str_repeat('- ', ++$level);
foreach ($src as $key => $val) {
echo $prefix . $key;
if ($val) {
nest_print($val, $level);
}
}
}
nest_print($out);
EDIT
Here is an alternate solution, including the count of final leaves, as asked by the OP in his comment:
$out = [];
foreach ($cat as $str) {
$lookup =& $out;
$parts = explode("/", $str);
foreach ($parts as $part) {
$lookup =& $lookup[$part];
if (!isset($lookup)) {
$lookup = [];
}
// when $part is a final leaf, count its occurrences
if ($part == end($parts)) {
$lookup = is_array($lookup) ? 1 : ++$lookup;
}
}
}
(might likely be improved in a more elegant way, though)
And here is how to modify the print-result snippet accordingly:
function nest_print($src, $level = 0) {
$prefix = '<br />' . str_repeat('- ', ++$level);
foreach ($src as $key => $val) {
echo $prefix . $key;
if (is_array($val)) {
nest_print($val, $level);
} else {
echo ': ' . $val;
}
}
}
nest_print($out);
Suppose, i have the fallowing json:
{
"foo.bar": 1
}
and i want to save this like this:
$array["foo"]["bar"] = 1
but i also can have more than 2 "parameters" in string. For example:
{
"foo.bar.another_foo.another_bar": 1
}
and i want to save this same way.
$array["foo"]["bar"]["another_foo"]["another_bar"] = 1
Any ideas how can i do that in case that i don't know how many parameters i have?
This is far from the nicest solution, but I've been programming all day so I'm a little tired, but I hope it gives you something to work off, or at least a working solution for the time being.
Here's the IDEone of it working: click
And here's the code:
$json = '{
"foo.bar": 1
}';
$decoded = json_decode($json, true);
$data = array();
foreach ($decoded as $key => $value) {
$keys = explode('.', $key);
$data[] = buildNestedArray($keys, $value);
}
print_r($data);
function buildNestedArray($keys, $value) {
$new = array();
foreach ($keys as $key) {
if (empty($new)) {
$new[$key] = $value;
} else {
array_walk_recursive($new, function(&$item) use ($key, $value) {
if ($item === $value) {
$item = array($key => $value);
}
});
}
}
return $new;
}
Output:
Array
(
[0] => Array
(
[foo] => Array
(
[bar] => 1
)
)
)
Wasn't sure whether your JSON string could have multiples or not so I made it handle the former.
Hope it helps, may come back and clean it up a bit in the future.
Start with a json_decode
Then build a foreach loop to break apart the keys and pass them to some kind of recursive function that creates the values.
$old_stuff = json_decode($json_string);
$new_stuff = array();
foreach ($old_stuff AS $key => $value)
{
$parts = explode('.', $key);
create_parts($new_stuff, $parts, $value);
}
Then write your recursive function:
function create_parts(&$new_stuff, $parts, $value)
{
$part = array_shift($parts);
if (!array_key_exists($part, $new_stuff)
{
$new_stuff[$part] = array();
}
if (!empty($parts)
{
create_parts($new_stuff[$part], $parts, $value);
}
else
{
$new_stuff = $value;
}
}
I have not tested this code so don't expect to just cut and past but the strategy should work. Notice that $new_stuff is passed by reference to the recursive function. This is very important.
Try the following trick for "reformatting" into json string which will fit the expected array structure:
$json = '{
"foo.bar.another_foo.another_bar": 1
}';
$decoded = json_decode($json, TRUE);
$new_json = "{";
$key = key($decoded);
$keys = explode('.', $key);
$final_value = $decoded[$key];
$len = count($keys);
foreach ($keys as $k => $v) {
if ($k == 0) {
$new_json .= "\"$v\"";
} else {
$new_json .= ":{\"$v\"";
}
if ($k == $len - 1) $new_json .= ":$final_value";
}
$new_json .= str_repeat("}", $len);
var_dump($new_json); // '{"foo":{"bar":{"another_foo":{"another_bar":1}}}}'
$new_arr = json_decode($new_json, true);
var_dump($new_arr);
// the output:
array (size=1)
'foo' =>
array (size=1)
'bar' =>
array (size=1)
'another_foo' =>
array (size=1)
'another_bar' => int 1
I need compare 2 arrays , the first array have one order and can´t change , in the other array i have different values , the first array must compare his id with the id of the other array , and if the id it´s the same , take the value and replace for show all in the same order
For Example :
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
The Result in this case i want get it´s this :
"1a-dogs","2a-cats","3a-birds","4a-walking"
If the id in this case 4a it´s the same , that entry must be modificate and put the value of other array and stay all in the same order
I do this but no get work me :
for($fte=0;$fte<count($array_1);$fte++)
{
$exp_id_tmp=explode("-",$array_1[$fte]);
$cr_temp[]="".$exp_id_tmp[0]."";
}
for($ftt=0;$ftt<count($array_2);$ftt++)
{
$exp_id_targ=explode("-",$array_2[$ftt]);
$cr_target[]="".$exp_id_targ[0]."";
}
/// Here I tried use array_diff and others but no can get the results as i want
How i can do this for get this results ?
Maybe you could use the array_udiff_assoc() function with a callback
Here you go. It's not the cleanest code I've ever written.
Runnable example: http://3v4l.org/kUC3r
<?php
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
function getKeyStartingWith($array, $startVal){
foreach($array as $key => $val){
if(strpos($val, $startVal) === 0){
return $key;
}
}
return false;
}
function getMergedArray($array_1, $array_2){
$array_3 = array();
foreach($array_1 as $key => $val){
$startVal = substr($val, 0, 2);
$array_2_key = getKeyStartingWith($array_2, $startVal);
if($array_2_key !== false){
$array_3[$key] = $array_2[$array_2_key];
} else {
$array_3[$key] = $val;
}
}
return $array_3;
}
$array_1 = getMergedArray($array_1, $array_2);
print_r($array_1);
First split the 2 arrays into proper key and value pairs (key = 1a and value = dogs). Then try looping through the first array and for each of its keys check to see if it exists in the second array. If it does, replace the value from the second array in the first. And at the end your first array will contain the result you want.
Like so:
$array_1 = array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2 = array("4a-walking","2a-cats");
function splitArray ($arrayInput)
{
$arrayOutput = array();
foreach ($arrayInput as $element) {
$tempArray = explode('-', $element);
$arrayOutput[$tempArray[0]] = $tempArray[1];
}
return $arrayOutput;
}
$arraySplit1 = splitArray($array_1);
$arraySplit2 = splitArray($array_2);
foreach ($arraySplit1 as $key1 => $value1) {
if (array_key_exists($key1, $arraySplit2)) {
$arraySplit1[$key1] = $arraySplit2[$key1];
}
}
print_r($arraySplit1);
See it working here:
http://3v4l.org/2BrVI
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
function merge_array($arr1, $arr2) {
$arr_tmp1 = array();
foreach($arr1 as $val) {
list($key, $val) = explode('-', $val);
$arr_tmp1[$key] = $val;
}
foreach($arr2 as $val) {
list($key, $val) = explode('-', $val);
if(array_key_exists($key, $arr_tmp1))
$arr_tmp1[$key] = $val;
}
return $arr_tmp1;
}
$result = merge_array($array_1, $array_2);
echo '<pre>';
print_r($result);
echo '</pre>';
This short code works properly, you'll get this result:
Array
(
[1a] => dogs
[2a] => cats
[3a] => birds
[4a] => walking
)