-1

I want to insert a value in between an array. Both arrays are dynamically generated. Here are a sample code

$orig_array = Array
(
    [r0] => Array
        (
            [c0] => Array
                (
                    [field] => tab
                    [label] => First Name
                    [fieldid] => tab1
                )
        )

    [r1] => Array
        (
            [c0] => Array
                (
                    [field] => text
                    [label] => email
                )
        )

    [r2] => Array
        (
            [c0] => Array
                (
                    [field] => text
                    [label] => state
                )

        )
)

$insert_array = Array
                (
                    [field] => text
                    [label] => First Name
                    [fieldid] => fname
                    [tabid] => tab1
                )

Now I want to insert the 2nd array after the r1 node. There are 2 conditions for the 2nd array to be inserted at a particular position. 1. The field is tab field ( field = tab ) and 2. There is a tab id in 2nd array that should correspond to fieldid in first array.

Aditya
  • 1,705
  • 2
  • 13
  • 16

2 Answers2

0

It only manage the rows, but you can do the same for the columns:

$orig_array=array_combine(range(0,count($orig_array)-1),$orig_array);

foreach($orig_array as $key=>$row)
    if($yourCondition==TRUE)
        array_splice($orig_array, $key, 0, [["c0"=>$insert_array]]);
//you can manage your insertions here, 
//and work on a "classical" multi-dimensional array (with numeric keys)
//wich is far more easy

$final_array=[];
foreach($orig_array as $key=>$row)
        $final_array["r".$key]=$row;

Edit: Code updated where $yourCondition is your condition that I didn't well understood. Because it's in a foreach loop, you may want to do if($row["c0"]["something"]==$something) where something is your id or your tab.

Pierre
  • 429
  • 3
  • 15
  • Thanks. I was also working on this approach, but here I don't know what will be the position of the array to be inserted. It only depends on a condition that the new array is part of particular array node. – Aditya Nov 22 '13 at 05:19
  • @Aditya what does look like this condition? `$newNode='r2';`? Can you update your question with this code? – Pierre Nov 22 '13 at 17:30
0

What if you simply rewrite the array?

$final_array = array();
foreach($orig_array as $key=>$data)
{
    $final_array[$key] = $data;

    if($key == 'r1')
        $data['r1'] = $insert_array;
}
Raffaele Izzia
  • 242
  • 1
  • 3
  • 14