2014-02-17 48 views
0

我想知道如何將由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 

$產品陣列:

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'],[ '標題']和[ '單元']從陣列並添加到$ 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" 
} 
} 

任何幫助將不勝感激。

回答

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

完全一樣!感謝您的快速響應,我一直認爲有一種神奇的方式,它會使它工作,很哈哈! – DrDog

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); 
相關問題