我正在尝试使用array_push()
,由于某些原因,没有任何东西被推入我的阵列。
这是我做的:
foreach ($intersect_sku_array as $key ) {
$inserted_array[] = $key;
}
// dd($inserted_array); at this point, it works
foreach ($valid_array as $key => $value ) {
if ( in_array( strtolower($key) , $intersect_sku_array )){
array_push($inserted_array, $value['name'] );
}
}
dd($inserted_array);
我有什么:
array (size=18795)
0 => string 'bs-0003r' (length=8)
1 => string 'bs-0003r-a488' (length=13)
2 => string 'bs-0003r-pe' (length=11)
3 => string 'bs-0004r' (length=8)
4 => string 'bs-0004r-hrp' (length=12)
5 => string 'bs-0006r' (length=8)
6 => string 'bs-0006r-cy5' (length=12)
7 => string 'bs-0006r-fitc' (length=13)
8 => string 'bs-0006r-hrp' (length=12)
9 => string 'bs-0007r' (length=8)
.... more
我正在尝试添加:
$value['name'] = string 'Rabbit Anti-TSHR Polyclonal Antibody' (length=36)
输出(与我的相同):
array (size=18795)
0 => string 'bs-0003r' (length=8)
1 => string 'bs-0003r-a488' (length=13)
2 => string 'bs-0003r-pe' (length=11)
3 => string 'bs-0004r' (length=8)
4 => string 'bs-0004r-hrp' (length=12)
5 => string 'bs-0006r' (length=8)
6 => string 'bs-0006r-cy5' (length=12)
7 => string 'bs-0006r-fitc' (length=13)
8 => string 'bs-0006r-hrp' (length=12)
9 => string 'bs-0007r' (length=8)
.... more
我希望有这样的东西:
'bs-0003R' =>
array (size=1)
'name' => string 'Rabbit Anti-TSHR Polyclonal Antibody' (length=36)
有人可以指出我做错了吗?
答案 0 :(得分:0)
array_push
不是此处的答案无论如何。尽管存在差异,我仍会尝试解决您的问题:
<?php
$intersect_sku_array = array( // known SKUs?
'bs-0003r',
'bs-0003r-a488',
'bs-0003r-pe',
'bs-0004r',
'bs-0004r-hrp',
'bs-0006r',
'bs-0006r-cy5',
'bs-0006r-fitc',
'bs-0006r-hrp',
'bs-0007r'
);
$valid_array = array( // SKU info that is available?
'bs-0003R' => array(
'name' => 'Rabbit Anti-TSHR Polyclonal Antibody'
)
);
var_dump($intersect_sku_array,$valid_array);
$inserted_array = array_flip($intersect_sku_array); // this works a little different than the `foreach` in the OP
var_dump($inserted_array); // see for yourself
foreach ( $valid_array as $key => $value ) {
$key = strtolower($key); // maintain the lowercase key
if ( isset($inserted_array[$key]) ) { // this will avoid creating new values below
$inserted_array[$key] = array('name'=>$value['name']); // apply the name property
}
}
var_dump($inserted_array);
?>
或者,您可能希望$valid_array
内的项目的全部内容,在这种情况下,您可以执行以下操作:
<?php
// ...
if ( isset($inserted_array[$key]) ) {
$inserted_array[$key] = $value; // copy the whole thing
}
// ...
?>