Created
April 24, 2017 10:23
-
-
Save milinmestry/ace527fcd80a64d6a23065c0b16b002f to your computer and use it in GitHub Desktop.
Get new array with specific columns from existing 2d array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$api_records = getDataFromAPI(); // Fetchh data from DB/ or from another API | |
$keys = array('productID' => '', 'code' => '', 'parentProductID' => ''); | |
$product_ids = getArrayFrom2dArray($api_records, $keys); | |
/** | |
* | |
* @param array $records [2 dimensional associative array] | |
* @param array $keys | |
* @return array | |
* | |
* $keys must be array key only. | |
* $keys = array('productID' => '', 'code' => '', 'parentProductID' => ''); | |
*/ | |
function getArrayFrom2dArray(array $records, $keys) { | |
return array_map( | |
function($arr) use ($keys) { | |
if (is_array($keys)) { | |
// This will only return the all those keys=>values which are exits in source array | |
return array_intersect_key($arr, $keys); | |
} | |
else { | |
// This will always return the parent_product_id in return array | |
// Irrespctive of that key is present in source array or not | |
$parent_id = (isset($arr['parentProductID'])) ? $arr['parentProductID'] : 0; | |
return array('productID' => $arr['productID'], 'sku' => $arr['code'], 'parentProductID' => $parent_id); | |
} | |
}, $records | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment