将相同的键和值添加到关联数组php

时间:2016-05-26 14:02:41

标签: php arrays

我有一个像这样的数组

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
        )

)

此数组我要添加一对catidpercentagename作为另一个 下一个键上的数组例如:

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

这是我的代码

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

但它会产生错误的输出。

4 个答案:

答案 0 :(得分: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++;
}

答案 1 :(得分:0)

您唯一需要做的是:

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

答案 2 :(得分:0)

你正在构建错误的数组:

将一个NEW元素推送到主$data数组,然后为该新元素指定catid / $ value的键/值:

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

然后你创建一个新的顶级percentage,并将零推入其中,然后同名:

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

你不能像这样构建一个多键数组。您需要构建一个临时数组,然后将整个数据推送到主数组:

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

$data[] = $temp;

或者用简写符号表示:

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

答案 3 :(得分:0)

您可以使用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);