I have an associative array of counts with brand_slug
keys and a 2d array to which I would like to append related count data.
$countArray = [
"abu-garcia" => 1,
"daiwa" => 4,
"shimano" => 4
];
$dataArray = [
[
"brand_id" => 36,
"brand_name" => "Abu Garcia",
"brand_slug" => "abu-garcia"
],
[
"brand_id" => 41,
"brand_name" => "Daiwa",
"brand_slug" => "daiwa"
],
[
"brand_id" => 41,
"brand_name" => "Daiwa",
"brand_slug" => "daiwa"
],
[
"brand_id" => 39,
"brand_name" => "Shimano",
"brand_slug" => "shimano"
],
[
"brand_id" => 39,
"brand_name" => "Shimano",
"brand_slug" => "shimano"
],
];
I want to create a new array which should look like this:
[
[
"brand_id" => 36,
"brand_name" => "Abu Garcia",
"brand_slug" => "abu-garcia",
"count" => 1
],
[
"brand_id" => 41,
"brand_name" => "Daiwa",
"brand_slug" => "daiwa",
"count" => 4,
],
[
"brand_id" => 41,
"brand_name" => "Daiwa",
"brand_slug" => "daiwa",
"count" => 4
],
[
"brand_id" => 39,
"brand_name" => "Shimano",
"brand_slug" => "shimano",
"count" => 4
],
[
"brand_id" => 39,
"brand_name" => "Shimano",
"brand_slug" => "shimano",
"count" => 4
],
];
I think I understand what you're trying to do...
If these are examples of your arrays:
$CountArray = array("abu-garcia"=>1,
"daiwa"=>4,
"shimano"=>4);
$DataArray = array(
array("brand_id"=>36, "brand_name"=>"Abu Garcia", "brand_slug"=>"abu-garcia"),
array("brand_id"=>41, "brand_name"=>"Daiwa", "brand_slug"=>"daiwa"),
array("brand_id"=>39, "brand_name"=>"Shimano", "brand_slug"=>"shimano")
);
Then loop through your second array to build a new array, and adding the count
key from the first array like this:
$i = 0;
foreach($DataArray as $ItemArray){
foreach($ItemArray as $Key=>$Value){
$NewArray[$i][$Key] = $Value;
$NewArray[$i]['count'] = 0;
if(isset($CountArray[$ItemArray['brand_slug']])){
$NewArray[$i]['count'] = $CountArray[$ItemArray['brand_slug']];
}
}
ksort($NewArray[$i]);
$i++;
}
print_r($NewArray);