PHP将数组添加到另一个没有键的数组

时间:2019-06-01 16:24:36

标签: php arrays

我需要创建以下数组:

android:sharedUserId="android.uid.system"

我目前正在努力将产品放入“ product_info”阵列中。对于要添加的每种产品,请使用以下行:

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:sharedUserId="android.uid.system"
        android:theme="@style/AppTheme">

这对于第一个效果很好。但是,添加另一个覆盖它。第二个问题是,添加了键,这些键不应该存在:

$data = array(
   "invoice_info" => array(
       ...
    ),
    "product_info => array(
        array(
           "name" => "product 1",
           ...
        ),
        array(
           "name => "product 2",
            ...
        )
    )
);

这是添加2个产品后的输出。仅包括第二个。我究竟做错了什么?

1 个答案:

答案 0 :(得分:1)

这将为您生成一个数组数组

function longestConsec(strarr, k) {
  var arr = [];
  if (strarr.length == 0 || k > strarr.length || k <= 0) {
    return "";
  }
  for (var i = 1; i < strarr.length; i++) {
    if (strarr[i].length > strarr[0].length && arr.length < k) {
      arr.push(strarr[i]);
    }
  }
  arr.join('');
  alert(arr);
}

longestConsec(["zone", "abigail", "theta", "form", "libe", "zas"], 2);

结果

$data = array(
    "invoice_info" => array(),
    "product_info" => array(),
    );

$data['product_info'][] = ['name' => 'prod1','qty'=>1, 'price'=> 44, 'sum'=>100];
$data['product_info'][] = ['name' => 'prod2','qty'=>22, 'price'=> 55, 'sum'=>200];

print_r($data);

现在,如果您已经做了类似的事情

Array
(
    [invoice_info] => Array
        (
        )

    [product_info] => Array
        (
            [0] => Array
                (
                    [name] => prod1
                    [qty] => 1
                    [price] => 44
                    [sum] => 100
                )

            [1] => Array
                (
                    [name] => prod2
                    [qty] => 22
                    [price] => 55
                    [sum] => 200
                )

        )

)

要创建$product_info =& $data['product_info']; 变量,请注意,必须使用$product_info,否则当您尝试分配新数组时,它将无法按预期工作。因此,将其添加到之前的代码中看起来像这样

=&

会产生结果

$data = array(
    "invoice_info" => array(),
    "product_info" => array(),
    );

$data['product_info'][] = ['name' => 'prod1','qty'=>1, 'price'=> 44, 'sum'=>100];
$data['product_info'][] = ['name' => 'prod2','qty'=>22, 'price'=> 55, 'sum'=>200];


$product_info =& $data['product_info'];

$product_info[] = ['name' => 'prod3','qty'=>99, 'price'=> 155, 'sum'=>300];

print_r($data);