PHP array to tree array - php

I have a problem I cannot fix. I have 2 arrays and a string. The first array contains the keys the second one should use. The first one is like this:
Array
(
[0] => foo
[1] => bar
[2] => hello
)
Now I need a PHP code that converts it to the second array:
Array
(
[foo] => Array
(
[bar] => Array
(
[hello] => MyString
)
)
)
The number of items is variable.
Can someone please tell me how to do this?

You should use references to solve this problem:
$a = array (0 => 'foo', 1 => 'bar', 2 => 'hello' );
$b = array();
$ptr = &$b;
foreach ($a as $val) {
$ptr[$val] = Array();
$ptr = &$ptr[$val];
}
$ptr = 'MyString';
var_dump($b);

All you need is :
$path = array(
0 => 'foo',
1 => 'bar',
2 => 'hello'
);
$data = array();
$t = &$data;
foreach ( $path as $key ) {
$t = &$t[$key];
}
$t = "MyString";
unset($t);
print_r($data);
See Live Demo

Related

mapping array in associative

I have the following array defined.
$a = Array
(
[0] => 30:27
[1] => 29:28
[2] => 30:27
)
$b = Array
(
[0] => 102186
[3] => 102991
[4] => 102241
)
I have used array_map($a,$b); But not what i want the result comes.
Always first to first key, second to second key, third to third key, I expect the following result...
$ab = $b = Array
(
[0] => 102186 [30:27]
[1] => 102991 [29:28]
[2] => 102241 [30:27]
)
Edit:
If the array keys doesn't match (thought it was a typo), then just reset the arrays by using $a = array_values($a) and $b = array_values($b) like this:
$a = array(
0 => "30:27",
1 => "29:28",
2 => "30:27"
);
$b = array(
0 => "102186",
3 => "102991",
4 => "102241"
);
// Reset keys
$a = array_values($a);
$b = array_values($b);
$ab = array();
for ($i=0; $i < count($a); $i++) {
$ab[] = "{$b[$i]} [{$a[$i]}]";
}
echo "<pre>";
print_r($ab);
echo "</pre>";
Outputs:
Array
(
[0] => 102186 [30:27]
[1] => 102991 [29:28]
[2] => 102241 [30:27]
)
Just loop over the 1st array and add the corresponding value from the 2nd one. You can actually use array_map for this:
$ab = array_map(function($aVal, $bVal){
return "$bVal [$aVal]";
}, $a, $b);
DEMO: https://eval.in/78684
USE:
$arrayFirst and $arraySecond - your input arrays;
$result = array();
for ($i=0; $i < count($arrayFirst); $i++) {
$result[] = "{$arraySecond[$i]} [{$arrayFirst[$i]}]";
}
var_dump ($result);
Or array_merge_recursive()
$array = array_merge_recursive($array1, $array2);

php create multidimensional array from flat one

I have an array like this:
<?php
$array = array( 0 => 'foo', 1 => 'bar', ..., x => 'foobar' );
?>
What is the fastest way to create a multidimensional array out of this, where every value is another level?
So I get:
array (size=1)
'foo' =>
array (size=1)
'bar' =>
...
array (size=1)
'x' =>
array (size=1)
0 => string 'foobar' (length=6)
<?php
$i = count($array)-1;
$lasta = array($array[$i]);
$i--;
while ($i>=0)
{
$a = array();
$a[$array[$i]] = $lasta;
$lasta = $a;
$i--;
}
?>
$a is the output.
What exactly are you trying to do? So many arrays of size 1 seems a bit silly.
you probably want to use foreach loop(s) with a key=>value pair
foreach ($array as $k=>$v) {
print "key: $k value: $v";
}
You could do something like this to achieve the array you asked for:
$newArray = array();
for ($i=count($array)-1; $i>=0; $i--) {
$newArray = array($newArray[$i]=>$newArray);
}
I'm confused about what you want to do with non-numeric keys (ie, x in your example). But in any case using array references will help
$array = array( 0 => 'foo', 1 => 'bar', x => 'foobar' );
$out = array();
$curr = &$out;
foreach ($array as $key => $value) {
$curr[$value] = array();
$curr = &$curr[$value];
}
print( "In: \n" );
print_r($array);
print( "Out : \n" );
print_r($out);
Prints out
In:
Array
(
[0] => foo
[1] => bar
[x] => foobar
)
Out :
Array
(
[foo] => Array
(
[bar] => Array
(
[foobar] => Array
(
)
)
)
)
You can use a recursive function so that you're not iterating through the array each step. Here's such a function I wrote.
function expand_arr($arr)
{
if (empty($arr))
return array();
return array(
array_shift($arr) => expand_arr($arr)
);
}
Your question is a little unclear since in your initial statement you're using the next value in the array as the next step down's key and then at the end of your example you're using the original key as the only key in the next step's key.

unique pairs storing in array in php

I am stuck at a scenerio where i need to save user input like... (in 1 go i get these reuslt)
$string = "'a':'php,'b':'.Net' ...
'c' 'java'
'c' 'php'
'c' 'java'
'a' 'php'
'a' 'java' ";
Now i need to store all these values in a database (only unique pairs).
WHat i tried so far, exploded $string with "," and stored everything in an array like
$array["a"] = "php";...but this will overwrite a = java too... //problem
I don't need to check in database that if they exist already or not..this is handled already (all dumped data in one go get a unique identifier).
All i need to do is to get unique pairs and dump into database...means
a = php, a = java, b = .net, c = java, c=php
Only solution i could see was...after exploding ...check for the pair in db against new unique identified...mysql_num_rows...if does not exist then dump else dont...
Is there any easy way...??
The best way for your purpose is to create the multidimensional array
<?php
$string = "'a':'php','b':'.Net','c':'java','c':'php','c':'java','a':'php','a':'java'";
$array = array();
$temp_arr = explode(",", $string);
foreach($temp_arr as $key=>$value)
{
list($tempkey,$tempValue) = explode(':', $value);
$tempKey = trim($tempkey,"'");
$tempValue = trim($tempValue,"'");
$array[$tempKey][] = $tempValue;
}
$array = array_map('array_unique',$array);
echo "<pre>";
print_r($array);
?>
output will be
Array
(
[a] => Array
(
[0] => php
[2] => java
)
[b] => Array
(
[0] => .Net
)
[c] => Array
(
[0] => java
[1] => php
)
)
$string = "'a':'php,'b':'.Net','c':'java','c':'php','c':'java','a':'php','a':'java'";
$temp = array_map(function($item) {
list($key, $value) = explode(':', $item);
return array(str_replace("'", "", $key) => str_replace("'", "", $value));
}, explode(",", $string));
$results = array();
foreach($temp as $item) {
$key = key($item);
if(!isset($results[$key]) || !in_array($item[$key], $results[$key])) {
$results[$key][] = $item[$key];
}
}
print_r($results);
Output:
Array
(
[a] => Array
(
[0] => php
[1] => java
)
[b] => Array
(
[0] => .Net
)
[c] => Array
(
[0] => java
[1] => php
)
)

Combine arrays to form multidimensional array in php

I know there's a ton of answers but I can't seem to get it right. I have the following arrays and what I've tried:
$a = array ( 0 => '1421' , 1 => '2241' );
$b = array ( 0 => 'teststring1' , 1 => 'teststring2' );
$c = array ( 0 => 'teststring3' , 1 => 'teststring4' );
$d = array ( 0 => 'teststring5' , 1 => 'teststring6' );
$e = array_combine($a, array($b,$c,$d) );
But with this I get the error array_combine() [function.array-combine]: Both parameters should have an equal number of elements.
I know it's because the $a's array values aren't keys. That's why I'm coming here to see if I could get some help with an answer that can help me make it look something like this:
array(2) {
[1421]=>array( [0] => teststring1
[1] => teststring3
[2] => teststring5
)
[2241]=>array( [0] => teststring2
[1] => teststring4
[2] => teststring6
)
}
If you have control over creating the arrays, you should create them like:
$a = array ('1421' ,'2241');
$b = array ('teststring1', 'teststring3', 'teststring5');
$c = array ('teststring2', 'teststring4', 'teststring6');
$e = array_combine($a, array($b,$c) );
If not, you have to loop over them:
$result = array();
$values = array($b, $c, $d);
foreach($a as $index => $key) {
$t = array();
foreach($values as $value) {
$t[] = $value[$index];
}
$result[$key] = $t;
}
DEMO
Here is a one-liner in a functional coding style. Calling array_map() with a null function parameter followed by the "values" arrays will generate the desired subarray structures. array_combine() does the key=>value associations.
Code (Demo)
var_export(array_combine($a, array_map(null, $b, $c, $d)));
Output:
array (
1421 =>
array (
0 => 'teststring1',
1 => 'teststring3',
2 => 'teststring5',
),
2241 =>
array (
0 => 'teststring2',
1 => 'teststring4',
2 => 'teststring6',
),
)
Super clean, right? I know. It's a useful little trick when you don't have control of the initial array generation step.
Here's a new version of array_merge_recursive which will handle integer keys. Let know how it goes.
$a = array ( 0 => '1421' , 1 => '2241' );
$b = array ( 0 => 'teststring1' , 1 => 'teststring2' );
$c = array ( 0 => 'teststring3' , 1 => 'teststring4' );
$d = array ( 0 => 'teststring5' , 1 => 'teststring6' );
$e = array_combine($a, array_merge_recursive2($b, $c, $d));
echo "<pre>";
print_r($e);
function array_merge_recursive2() {
$args = func_get_args();
$ret = array();
foreach ($args as $arr) {
if(is_array($arr)) {
foreach ($arr as $key => $val) {
$ret[$key][] = $val;
}
}
}
return $ret;
}

Help understanding a php function - the meaning of $array[]; the [] part

private function jsonArray($object)
{
$json = array();
if(isset($object) && !empty($object))
{
foreach($object as $obj)
{
$json[]["name"] = $obj;
}
}
return $json;
}
We are grabbing an object, and if the conditional is met, we iterate over that object.
Then... I'm lost on this reading... :s
What's the meaning of the [] here?
$json[]["name"] = $obj;
Thanks in advance,
MEM
$json[] adds an element at the end of the array (numeric index). It's the same as having the following code:
$array=array();
$i=0;
foreach($something as $somethingElse)
{
$array[]=$somethingElse;
//is equivalent, in some way, to
$array[$i++]=$somethingElse;
}
That's the equivalent to this:
$json[] = array('name' => $obj);
It adds the contents of $obj to a new field in $json and there in the field "name".
Little example:
$arr = array();
$arr[] = "Hello";
$arr[] = "World!";
Then, $arr will contain:
Array (
0 => "Hello",
1 => "World!"
)
Or, as in your example with another array in the field:
$arr = array();
$arr[]["text"] = "Hello";
$arr[]["text"] = "World!";
Becomes
Array (
0 => Array (
"text" => "Hello"
),
1 => Array (
"text" => "World!"
)
)
$json[] automatically creates a new element at the end of the array - here is an example:
$json[]["name"] = "object1";
$json[]["name"] = "object2";
$json[]["name"] = "object3";
$json[]["name"] = "object4";
And here is what it displays:
Array
(
[0] => Array
(
[name] => object1
)
[1] => Array
(
[name] => object2
)
[2] => Array
(
[name] => object3
)
[3] => Array
(
[name] => object4
)
)

Categories