0

I have an array generated by PHP

array(
  array(
  'name'=>'node1',
  'id' => '4'
   ),
  array(
  'name'=>'node2'
  'id'=>'7'
  )
)

And I am trying to add an array to a specific id (so let's say id 4)

'children'=>
        array(
          array('name'=>'node2','id'=>'5'),
          array('name'=>'node3','id'=>'6')
        )

So then it would look like

array(
  array(
  'name'=>'node1',
  'id' => '4'
  'children'=>
        array(
          array('name'=>'node2','id'=>'5'),
          array('name'=>'node3','id'=>'6')
        )
   ),
  array(
  'name'=>'node2'
  'id'=>'7'
  )
)

but I can't seem to figure out a way to search a multidimensional array, and add a multidimensional array to that array.

Any help?

3 Answers 3

2

Use a foreach loop to iterate through the array (making sure to get the key too), check the value, add if needed and break when found.

foreach($array as $k=>$v) {
    if( $v['id'] == 4) {
        $array[$k]['children'] = array(...);
        break;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0
foreach($a as $k => $v)
{
  if(is_array($v))
  {
   foreach($v as $ke => $va)
   {
    if($ke == 'children')
    {
     ......
    }
   }
 }
}

Comments

0

It's a monstrosity but it does what you want. Using push in a recursive function fails because the reference is destroyed after the second function call, so if you don't know how deep the key is there's a choice between using an arbitrary number of loops and hoping for the best, importing variables and using eval to push new values, or pulling apart and rebuilding the array. I chose eval. The description of what you wanted is a little different from pushing a value because you're looking for a key-value pair within an array, not an array. This function finds the key value pair and adds whatever you want as a sibling, if no value is specified the value is added as sibling to the first key matched. If no pushval is specified it will return the chain of keys that points to the matched key/key-value.

$ref_array is the multi-array to be modified, $key is the key you're looking for, $val is the value of the key you're looking for, $newkey is the new key that will reference the new value, $pushval is the new value to be indexed by $newkey.

DON'T pass an argument for the $val_array parameter. It's for use with recusive calls only. It's how the function distinguishes new calls from recursive calls, and it's how the function finds the key-value without disrupting the pass-by-reference.

function deepPush(&$ref_array, $key, $val=null, $newkey=null, $pushval=null, $val_array=null)
{
    static $r, $keys;

    #reset static vars on first call
    if(!$val_array){ $r = 0; $keys = array();}
    #cap recursion
    if($r > 100){ trigger_error('Stack exceeded 100'); return;}
    #init val_array
    $val_array = ($r) ? $val_array : $ref_array;
    #specified search value???
    $search_val = ($val!==null && !in_array($val, $val_array)) ? true : false;
    if(!array_key_exists($key, $val_array) || $search_val) {
    $i=0;foreach($val_array as $k=>$v){
            if(gettype($v) == 'array') {
                if($i>0){/*dead-end*/array_pop($keys); /*keep recusion accurate*/$r-=$i;}
                $keys[] = $k;/*build keychain*/
                $r++; $i++; /*increment recursion, iteration*/
                if(deepPush($ref_array, $key, $val, $newkey, $pushval, $v)){ /*close stack on 1st success*/return $keys;}
            }//if
        }//foreach
    }//if
    else{
        if($pushval === null){return $keys;}
        #add $newkey to the keychain
        $keys[] = $newkey;
        #process $pushval based on type
        $pushval = (gettype($pushval) == 'string') ? sprintf("'%s'", $pushval) : var_export($pushval, true);

        #link keys together to form pointer
        $p = '$ref_array';
        for($j=0,$c=count($keys); $j<$c; $j++) {
            $k = $keys[$j];
            $p .= "['$k']";
        }//for

        #concat the value to be pushed
        $p .= sprintf("= %s;",$pushval);
        #push it
        eval($p);

        $keys = array();
        return true;

    }//else

}

deepPush($array, 'id', 4, 'children', $addThis);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.