Blessan Kurien Blessan Kurien - 6 months ago 33
PHP Question

Adding same key and values to associative array php

I have an array like this

Array
(
[0] => Array
(
[catid] => 1
[percentage] => 4
[name] => Access Control
)

[1] => Array
(
[catid] => 7
[percentage] => 1
[name] => Audio Video
)

[2] => Array
(
[catid] => 5
[percentage] => 1
[name] => Home Automation
)

)


tho this array i want to add a pair of
catid
,
percentage
and
name
as another
array on the next key eg:

[3] => Array
(
[catid] => 7
[percentage] => 0
[name] => 'some name'
)


Here is my code

//another array
$id=array('1','2',....n);
//$data is my original array
foreach($id as $key=>$value){
$data[]['catid']=$value;
$data['percentage'][]='0';
$data['name'][]='Some name';
}


But it will give wrong output.

Answer
//another array
$id=array('1','2',....n);
$i = count($data);
//$data is my  original array
foreach($id as $key=>$value){
      $data[$i]['catid']=$value;
      $data[$i]['percentage']='0';
      $data[$i]['name']='Some name';
      $i++;
}