Blessan Kurien
Blessan Kurien

Reputation: 1665

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

Upvotes: 0

Views: 4047

Answers (4)

splash58
splash58

Reputation: 26153

//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++;
}

Upvotes: 1

Pedro Lobito
Pedro Lobito

Reputation: 98881

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);

Upvotes: 0

Marc B
Marc B

Reputation: 360602

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');

Upvotes: 0

Daan
Daan

Reputation: 12236

The only thing you need to do is:

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

Upvotes: 0

Related Questions