hierarchial two dimetional php array from an two dimetional php - php

I have a multiD array containing all users like below.
Array
(
[0] => Array
(
[username] => santoshe62
[sponsor] => santoshe61
)
[1] => Array
(
[username] => santoshe63
[sponsor] => santoshe62
)
[2] => Array
(
[username] => santoshe65
[sponsor] => santoshe64
)
[3] => Array
(
[username] => santoshe67
[sponsor] => santoshe66
)
.............................
)
I want an array from this array containing hierarchical data of given user like below.
Array
(
[0] => Array
(
[username] => santoshe62
[sponsor] => santoshe61
)
[1] => Array
(
[username] => santoshe63
[sponsor] => santoshe62
)
)
I have tried
function parseTree($datas, $parent = 0){
$tree = array();
for($i=0, $ni=count($datas); $i < $ni; $i++){
if($datas[$i]['sponsor'] == $parent){
$tree[] = $datas[$i];
parseTree($datas, $datas[$i]['username']);
}
}
return $tree;
}
Can anybody help me by finding what is wrong in my code? Also please suggest, can I select only this hierarchical structure directly from MySQL? Now I am selecting all results from DB.

The problem is because of this statement in your function, $tree = array();. In each recursive function call, this $tree is getting initialized with an empty array. You have to declare it as static variable, so that it could get initialized only once and could retain its state in recursive function calls.
function parseTree($datas, $parent = 0){
static $tree = array();
...
}

Related

How to update an Associative Array

I do not know what is wrong with my php code. I want to have an Associative Array in the format. When I run my code I get this data. [KY] is an array in the [OH] array.
Array ( [Oh] => Array ( [state] => Oh ) [income] => 100 [count] => 1 [Ky] => Array ( [state] => Ky ) )
Array (
[OH] => Array
( [income] =>
[count] =>
)
[KY] => Array
( [income] =>
[count] =>
)
Here is my code
Example data in $array
Array ( [0] => Array (
[SurveyDate] => 1952-06-21
[Income] => 100
[CountyState] => Hamilton|Oh
[count] => 1 ) )
function update_array_value3( $array )
{
foreach ($array as $row)
{
$arrCountyState = explode( "|", $row['CountyState'] );
$key = $arrCountyState[1]; // OH or KY
if( !isset( $_SESSION['sIncome'][$key] ) )
{
$_SESSION['sIncome'][$key]['state'] = $key;
$_SESSION['sIncome'][$key]['income'] = $row['Income'];
$_SESSION['sIncome'][$key]['count'] = 1;
} else
{
$_SESSION['sIncome'][$key]['state'] = $key;
$_SESSION['sIncome'][$key]['income'] += $row['Income'];
$_SESSION['sIncome'][$key]['count'] += 1;
}
}
I can't tell you the root cause of the problem simply based on this snippet of code, but it seems $row either doesn't contain the data you expect it to, or doesn't contain any data.
In your code you reference $row['CountyState'], yet I don't see any array item called CountyState in $array.
Also, I'm not sure whether or not this is intentional, but in your foreach() loop it looks like $_SESSION['sIncome']['income'] and $_SESSION['sIncome']['count'] are being overwritten. Each time the loop encounters a new $key, it will overwrite those values.

How do I add keys recursively to an array

I have a query result set which I loop through. Depending on the data inside the result set, I want to add it to the array, or if the specific value contains an ID, loop again, and add it at the current position. I want to end up with something like this.
Array
(
[0] => Array
(
[title] => Array
(
[0] => Array
(
[value] => Lorem ipsum
)
)
[uid] => Array
(
[0] => Array
(
[uid] => Array
(
[value] => 1
)
[field_name] => Array
(
[value] => John Doe
)
)
)
)
)
I accomplished the result, but I'm looping over and over again, I would like it to be recursive. So I ended up doing something like this.
foreach ($fields as $nr => $field){
if ($field_type == 'entity_reference'){
// Query again
...
foreach ($fields2 as $nr2 => $field2){
if ($field_type2 == 'entity_reference'){
// Query again
...
} else {
$return[$nr][$field][$nr2][$fieldl2] = $value2;
}
}
} else {
$return[$nr][$field][] = $value;
}
}
How can I make it recursive, so I don't have to loop many times?

How to insert item on every item in an array using PHP

I have this existing array
Array
(
[0] => stdClass Object
(
[userid] => 1
[user] => John Doe
)
[1] => stdClass Object
(
[userid] => 2
[user] => Mae Smith
)
)
I want to insert new item in each array like [randomNumber] => 50. So the final output must be like this
Array
(
[0] => stdClass Object
(
[userid] => 1
[user] => John Doe
[randomNumber] => 25
)
[1] => stdClass Object
(
[userid] => 2
[user] => Mae Smith
[randomNumber] => 50
)
)
I'm using php using for loop to insert the randomNumber every user
for($i=0 ; $i<count($users) ; $i++) {
// insert randomNumber here
$users[$i] = array('randomNumber' => rand(10,100));
}
It doesn't seems to work. What should be the proper way? Thanks
Iterate with a foreach, and as $user is an object, it will be passed to loop by reference:
foreach ($users as $user) {
$user->randomNumber = rand(10,100);
}
As you have an array of objects rather than arrays...
for($i=0 ; $i<count($users) ; $i++) {
// insert randomNumber here
$users[$i]->randomNumber = rand(10,100);
}
I think foreach function is better for you. and you have array of objects.
foreach ($users as $key => $value) {
$users[$key]->randomNumber = rand(10,100);
}

PHP: array_splice() not giving me correct output

I'm trying to experiment with array_splice and I get an output like this (from $match)
Array
(
[Keep me Updated] => Array
(
[winner] => winnerl.jpg
[0] => value0.jpg
)
[0] => valuel.jpg //this should really be inside [Leep me Updated] array
[1] => value2.jpg //this should really be inside [Leep me Updated] array
[2] => value3.jpg //this should really be inside [Leep me Updated] array
}
from (this foreach creates puts in the values into $match)
foreach($data as $d)
{
if (isset($match[$d['data']['name']])) {
$match_loser = array($d['loser']['lrg_img']);
array_splice($match,1,0,$match_loser);
}else{
$match[$d['data']['name']] = array("winner"=>$d['winner']['lrg_img'],
$d['loser']['lrg_img']);
}
}
What I'm trying to get is bring [0],[1],[2] into the [Keep me Updated] $match array:
Array
(
[Keep me Updated] => Array
(
[winner] => winnerl.jpg
[0] => value0.jpg
[1] => value1.jpg // old one: [0] => valuel.jpg
[2] => value2.jpg // old one: [1] => value2.jpg
[3] => value3.jpg // old one: [2] => value3.jpg
)
}
This is what $data looks like
$data[] = array(
"data"=>array
(
"name"=>$name,
),
"winner"=>array
(
"lrg_img"=>$img_url_winner
),
"loser"=>array
(
"lrg_img"=>$img_url_loser
)
$data has array values, and $match is where I'm trying to sort the data. So if my values match, it'll consolidate.
Thanks!
Use the inner array as the argument to array_splice
foreach($data as $d)
{
if (isset($match[$d['data']['name']])) {
$match_loser = array($d['loser']['lrg_img']);
array_splice($match[$d['data']['name']],1,0,$match_loser);
}else{
$match[$d['data']['name']] = array("winner"=>$d['winner']['lrg_img'],
$d['loser']['lrg_img']);
}
}

How can I create multidimensional arrays from a string in PHP?

So My problem is:
I want to create nested array from string as reference.
My String is "res[0]['links'][0]"
So I want to create array $res['0']['links']['0']
I tried:
$result = "res[0]['links'][0]";
$$result = array("id"=>'1',"class"=>'3');
$result = "res[0]['links'][1]";
$$result = array("id"=>'3',"class"=>'9');
when print_r($res)
I see:
<b>Notice</b>: Undefined variable: res in <b>/home/fanbase/domains/fanbase.sportbase.pl/public_html/index.php</b> on line <b>45</b>
I need to see:
Array
(
[0] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 1
[class] => 3
)
)
)
[1] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 3
[class] => 9
)
)
)
)
Thanks for any help.
So you have a description of an array structure, and something to fill it with. That's doable with something like:
function array_create(&$target, $desc, $fill) {
preg_match_all("/[^\[\]']+/", $desc, $uu);
// unoptimized, always uses strings
foreach ($uu[0] as $sub) {
if (! isset($target[$sub])) {
$target[$sub] = array();
}
$target = & $target[$sub];
}
$target = $fill;
}
array_create( $res, "[0]['links'][0]", array("id"=>'1',"class"=>'3') );
array_create( $res, "[0]['links'][1]", array("id"=>'3',"class"=>'9') );
Note how the array name itself is not part of the structure descriptor. But you could theoretically keep it. Instead call the array_create() function with a $tmp variable, and afterwards extract() it to achieve the desired effect:
array_create($tmp, "res[0][links][0]", array(1,2,3,4,5));
extract($tmp);
Another lazy solution would be to use str_parse after a loop combining the array description with the data array as URL-encoded string.
I have a very stupid way for this, you can try this :-)
Suppose your string is "res[0]['links'][0]" first append $ in this and then put in eval command and it will really rock you. Follow the following example
$tmp = '$'.'res[0]['links'][0]'.'= array()';
eval($tmp);
Now you can use your array $res
100% work around and :-)
`
$res = array();
$res[0]['links'][0] = array("id"=>'1',"class"=>'3');
$res[0]['links'][0] = array("id"=>'3',"class"=>'9');
print_r($res);
but read the comments first and learn about arrays first.
In addition to mario's answer, I used another function from php.net comments, together, to make input array (output from jquery form serializeArray) like this:
[2] => Array
(
[name] => apple[color]
[value] => red
)
[3] => Array
(
[name] => appleSeeds[27][genome]
[value] => 201
)
[4] => Array
(
[name] => appleSeeds[27][age]
[value] => 2 weeks
)
[5] => Array
(
[name] => apple[age]
[value] => 3 weeks
)
[6] => Array
(
[name] => appleSeeds[29][genome]
[value] => 103
)
[7] => Array
(
[name] => appleSeeds[29][age]
[value] => 2.2 weeks
)
into
Array
(
[apple] => Array
(
[color] => red
[age] => 3 weeks
)
[appleSeeds] => Array
(
[27] => Array
(
[genome] => 201
[age] => 2 weeks
)
[29] => Array
(
[genome] => 103
[age] => 2.2 weeks
)
)
)
This allowed to maintain numeric keys, without incremental appending of array_merge. So, I used sequence like this:
function MergeArrays($Arr1, $Arr2) {
foreach($Arr2 as $key => $Value) {
if(array_key_exists($key, $Arr1) && is_array($Value)) {
$Arr1[$key] = MergeArrays($Arr1[$key], $Arr2[$key]);
}
else { $Arr1[$key] = $Value; }
}
return $Arr1;
}
function array_create(&$target, $desc, $fill) {
preg_match_all("/[^\[\]']+/", $desc, $uu);
foreach ($uu[0] as $sub) {
if (! isset($target[$sub])) {
$target[$sub] = array();
}
$target = & $target[$sub];
}
$target = $fill;
}
$input = $_POST['formData'];
$result = array();
foreach ($input as $k => $v) {
$sub = array();
array_create($sub, $v['name'], $v['value']);
$result = MergeArrays($result, $sub);
}

Categories