0

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,percentageand 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.

1
  • array_push($old, $new); let you have old one as main and want to add the new one at the last of the main. Commented May 26, 2016 at 14:07

4 Answers 4

1
//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++;
}
Sign up to request clarification or add additional context in comments.

2 Comments

This worked but last associative array is missing from the orignal array
Changed $i=count($data) now its woked
0

The only thing you need to do is:

$yourArray[] = [
    'catid' => 7,
    'percentage' => 0,
    'name' => 'some name'
];

Comments

0

You're building the array wrong:

This pushes a NEW element onto the main $data array, then assigns a key/value of catid/$value to that new element:

  $data[]['catid']=$value;

Then you create a new top-level percentage, and push a zero into it, and ditto for name:

  $data['percentage'][]='0';
  $data['name'][]='Some name';'

You can't build a multi-key array like this. You need to build a temporary array, then push the whole thing onto the main array:

$temp = array();
$temp['catid'] = $value;
$temp['percentage'] = 0;
$temp['name'] = 'Some name';

$data[] = $temp;

Or in shorthand notation:

$data[] = array('catid' => $value, 'percentage' => 0, 'name' = 'Somename');

Comments

0

You can use array_push

$a1 = array(array('catid' => '1', 'percentage' => '4', 'name' => 'Access Control'));
$a2 = array('catid' => '7', 'percentage' => '0', 'name' => 'Some Name');
array_push($a1 ,$a2);
print_r($a1);

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.