将关联数组的部分推入另一个

时间:2014-02-17 09:34:39

标签: php arrays multidimensional-array foreach

我想知道如何将foreach循环产生的关联数组的某些部分推入另一个数组。

代码:

foreach ($result as $product) {
    $liveArray = $product['prodid']['title']['unit'];
    insertData($dbh, $product);
  }
} while (!empty($rule)); //Stops loops if last element on page is found
foreach循环后的

$ product数组:

array(5) {
  ["prodid"]=>
  string(6) "123456"
  ["title"]=>
  string(29) "Test item 1"
  ["unit"]=>
  string(4) "100pk "
  ["price"]=>
  string(4) "10.99"
  ["wasprice"]=>
  string(4) "11.99"
}

我只想从数组中获取['prodid'],['title']和['unit']并添加到$ liveArray。导致这样的事情:

  array(1) {
    [0]=>
    array(5) {
  ["prodid"]=>
  string(6) "123456"
  ["title"]=>
  string(29) "Test item 1"
  ["unit"]=>
  string(4) "100pk "
  ["price"]=>
  string(4) "10.99"
  ["wasprice"]=>
  string(4) "11.99"
}
    [1]=>
    array(5) {
  ["prodid"]=>
  string(6) "123457"
  ["title"]=>
  string(29) "Test item 2"
  ["unit"]=>
  string(4) "50pk "
  ["price"]=>
  string(4) "11.00"
  ["wasprice"]=>
  string(4) "13.00"
}
}

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

像这样?

$liveArray = array();
do {
    foreach ($result as $product) {
        $liveArray[] = array(
            'prodid' => $product['prodid'],
            'title' => $product['title'],
            'unit' => $product['unit'],
        );
        insertData($dbh, $product);
    }
} while (!empty($rule)); //Stops loops if last element on page is found
// print_r( $liveArray );

答案 1 :(得分:1)

//附加为更好格式化的答案。

DrDog,如果你想要一种神奇的方式,那就是:

$liveArray = array();
$keepKeys = array('prodid' => true, 'title' => true, 'unit' => true, );
/* or more magic
$keepKeys = array('prodid', 'title', 'unit', );
$keepKeys = array_flip($keepKeys);
*/
do {
    foreach ($result as $product) {
        $liveArray[] = array_intersect_key($product, $keepKeys);
        insertData($dbh, $product);
    }
} while (!empty($rule)); //Stops loops if last element on page is found
// print_r( $liveArray );