I have an array from a feed with following print_r output:
Array
(
[0] => Array
(
[name] => Cell Phone Case
[options] => Array
(
[Colors] => Array
(
[0] => Clear
[1] => Red
[2] => Blue
)
)
Array
(
[1] => Array
(
[name] => Iphone
)
Array
(
[2] => Array
(
[name] => Tablet
[options] => Array
(
[Color] => Array
(
[0] => White
[1] => Black
[2] => Red
)
)
The feed unfortunately is providing colors in two values, for some products it is:
options['Colors']
and for some other
options['Color'].
My code to insert the values into DB is as follows:
$stmt = $conn->prepare("INSERT INTO product_colors(product_id, colors) VALUES(:pid, :colors)");
if (!is_array($value['options']['Colors'])) {
$value['options']['Colors'] = array($value['options']['Colors']);
}
if (!is_array($value['options']['Color'])) {
$value['options']['Color'] = array($value['options']['Color']);
}
//Colors or Color
$colorArr = array();
if(isset($value['options']['Colors'])) {
$colorArr = $value['options']['Colors'];
}
if(isset($value['options']['Color'])) {
$colorArr = array_merge($colorArr, $value['options']['Color']);
}
$PID = ($conn->lastInsertId());
foreach ($colorArr as $colors) {
$stmt->execute(array(':pid' => $PID, ':colors' => $colors));
}
The data is getting inserted except that a null value is also inserted at the beginning, except for product 1 (at end ) for each product color values.
print_r($colorArr); gives the following array output:
Array
(
[0] => Clear
[1] => Red
[2] => Blue
[3] =>
)
An extra null value after the 3 colors for product 1...
Please note that some products do not have color value like the iphone in array 2.
How can i correct this issue ??? I need the product colors inserted into DB for the corresponding product id, even if options are both Colors or Color.
Help requested....
Update:
I have corrected the issue myself. The default php array_merge function doesn't merge values if any subsequent array's field is empty. This function rectifies it as follows:
function array_merge_corrected($array_a=array(),$array_b=array()){
$array_merge= array();
if(!empty($array_a)&& !empty($array_b)){
foreach($array_a as $field=>$value){
$array_merge[$field]= $value;
}
foreach($array_b as $field=>$value){
if(!empty($value)){
$array_merge[$field]= $value;
} elseif(!array_key_exists($field,$array_a)){
$array_merge[$field]= $value;
}
}
}
return $array_merge;
}
$colorArr = array_merge_corrected($colorArr, $value['options']['Color']);