Loop PHP array based in first array - php

I just found out how to loop an array based on another array, but my problem is that if the second array is just 1 object than it works fine but I want to make it work with two objects.
Here is an example how it do works,
$shorten = array(
0 => 'ECAR',
1 => 'CCAR',
2 => 'ICAR',
3 => 'SCAR',
4 => 'FCAR',
5 => 'PCAR',
);
$data = array(
'Hertz' => array(
'ECAR' => '49.21',
'CCAR' => '71.04',
'ICAR' => '89.58',
'SCAR' => '100.00',
)
),
'Avis' => array(
'ECAR' => '412.00',
'CCAR' => '347.00',
'ICAR' => '285.00',
'SCAR' => '224.00',
'FCAR' => '165.00',
'PCAR' => '100.00',
)
),
);
// default array as the base
$shorten = array_combine($shorten, array_fill(0, count($shorten), 'n/a'));
foreach($data as &$array) {
// merge to get set members
$array = array_merge($shorten, $array);
}
unset($array);
print_r($data);
But I want to make it work with this one,
$shorten = array(
0 => 'ECAR',
1 => 'CCAR',
2 => 'ICAR',
3 => 'SCAR',
4 => 'FCAR',
5 => 'PCAR',
);
$data = array(
'Hertz' => array(
'NYCT01' => array(
'ECAR' => '49.21',
'CCAR' => '71.04',
'ICAR' => '89.58',
'SCAR' => '100.00',
)
),
'Avis' => array(
'NYCT01' => array(
'ECAR' => '412.00',
'CCAR' => '347.00',
'ICAR' => '285.00',
'SCAR' => '224.00',
'FCAR' => '165.00',
'PCAR' => '100.00',
)
),
);
// default array as the base
$shorten = array_combine($shorten, array_fill(0, count($shorten), 'n/a'));
foreach($data as $firstArray) {
foreach($firstArray as &$array){
// merge to get set members
$array = array_merge($shorten, $array);
}
}
unset($array);
print_r($data);
And this is what I want it to be,
Array
(
[Hertz] => Array
(
[ECAR] => 49.21
[CCAR] => 71.04
[ICAR] => 89.58
[SCAR] => 100.00
[FCAR] => n/a
[PCAR] => n/a
)
[Avis] => Array
(
[ECAR] => 412.00
[CCAR] => 347.00
[ICAR] => 285.00
[SCAR] => 224.00
[FCAR] => 165.00
[PCAR] => 100.00
)
)

foreach($data AS $company => $nyc){
$inner = $nyc['NYCT01'];
foreach($shorten AS $car){
if(array_key_exists($car, $inner)){
$output[$company][$car] = $inner[$car];
}else {
$output[$company][$car] = "n/a";
}
}
}
Just loop through the data and check if the key of any of the cars exists inside the NYCT01 array, if it does set the value, else, "n/a".
My output:
Array
(
[Hertz] => Array
(
[ECAR] => 49.21
[CCAR] => 71.04
[ICAR] => 89.58
[SCAR] => 100.00
[FCAR] => n/a
[PCAR] => n/a
)
[Avis] => Array
(
[ECAR] => 412.00
[CCAR] => 347.00
[ICAR] => 285.00
[SCAR] => 224.00
[FCAR] => 165.00
[PCAR] => 100.00
)
)

Ok, got it work this is the real code I figured,
foreach($data as $company => $nyc){
foreach($nyc as $inner => $s){
foreach($shorten as $car){
if(array_key_exists($car, $nyc[$inner])){
$output[$company][$car] = $nyc[$inner][$car];
}else {
$output[$company][$car] = "n/a";
}
}
}
}
Thanks so much for your help Marcus,
Good luck.

Related

How to merge two array if one item exist in both array?

I want to expand my city array with post code value.
If the city_postcode array contain city array name record then push postcode value into city array. That's what i want to achive somehow.
city array:
Array
(
[0] => Array
(
[id] => 1
[city] => Budapest
[population] => 1700000
)
[1] => Array
(
[id] => 2
[city] => Szeged
[population] => 160000
)
)
city_postcode array:
Array
(
[0] => Array
(
[name] => Budapest
[post_code] => 12345
)
[1] => Array
(
[name] => Szeged
[post_code] => 33356
)
)
The result I want:
Array
(
[0] => Array
(
[id] => 1
[city] => Budapest
[population] => 1700000
[post_code] => 12345
)
[1] => Array
(
[id] => 2
[city] => Szeged
[population] => 160000
[post_code] => 33356
)
)
If you can rely on the cities and post codes to be equal in length and sorted, you could just do something like this:
<?php
$cities = array(
array("id"=>1,"city"=>"Budapest","Population"=>"1700000"),
array("id"=>2,"city"=>"Szeged","Population"=>"160000")
);
$cityPostCode = array(
array("name"=>"Budapest","post_code"=>12345),
array("name"=>"Szeged","post_code"=>33356)
);
for($i = 0; $i < count($cities); $i++){
$cities[$i]['post_code'] = $cityPostCode[$i]['post_code'];
}
print_r($cities);
Other wise you could do something more dyanmic like:
function _parsePostCode($targetName,$targetArr){
foreach($targetArr as $el){
if($el['name'] == $targetName){
return $el['post_code'];
}
}
return false;
}
for($i = 0; $i < count($cities); $i++){
$cities[$i]['post_code'] = _parsePostCode($cities[$i]['city'],$cityPostCode);
}
print_r($cities);
As an alternative you can use 'reference' PHP in foreach loop as follows
$city = array(
0 => array(
'id' => 1,
'city' => "Budapest",
'population' => 1700000
),
1 => array(
'id' => 2,
'city' => "Szeged",
'population' => 160000
)
);
$city_postcode = array(
0 =>array(
'name' => 'Budapest',
'post_code' => 12345
),
1 => array(
'name' => 'Szeged',
'post_code' => 33356
)
);
foreach ($city as $ckey => &$cval) {
$cval['post_code'] = $city_postcode[$ckey]['post_code'];
}
unset($cval);
var_dump($city);
You can use this simple approach :
<?php
$city = array(
0 => array(
'id' => 1,
'city' => "Budapest",
'population' => 1700000
),
1 => array(
'id' => 2,
'city' => "Szeged",
'population' => 160000
)
);
$city_postcode = array(
0 => array(
'name' => 'Budapest',
'post_code' => 12345
),
1 => array(
'name' => 'Szeged',
'post_code' => 33356
)
);
function apply_post_code(&$item, $key, $postcode)
{
$item['post_code'] = $postcode[ $key ][ 'post_code' ];
}
array_walk($city, 'apply_post_code', $city_postcode);
var_dump($city);
Note that the $city variable has been passes by reference

PHP array merge based on key & value

I have one array and try to change some key and value for example if sku are same than i need to merge image. Below array i have
Array
(
[0] => Array
(
[sku] => h-eldora
[name] => H ELDORA
[image] => s/files/1/1282/4221/products/h_eldora_01.jpg?v=1476667054
)
[1] => Array
(
[sku] => h-eldora
[name] =>
[image] => s/files/1/1282/4221/products/h_eldora_02.jpg?v=1475116221
)
[2] => Array
(
[sku] => h-eldora
[name] =>
[image] => s/files/1/1282/4221/products/20100707164858197_1_88da6866-701a-42b9-b523-5e454cbcce70.jpg?v=1475717598
)
[3] => Array
(
[sku] => hl-dracy
[name] => HL DRACY
[image] => s/files/1/1282/4221/products/h_dracy_01.jpg?v=1475115222
)
[4] => Array
(
[sku] => hl-dracy
[name] =>
[image] => s/files/1/1282/4221/products/h_dracy_02.jpg?v=1475115223
)
[5] => Array
(
[sku] => hl-dracy
[name] =>
[image] =>s/files/1/1282/4221/products/20100707164858197_1_633237aa-36ec-441b-a074-03844f6a0858.jpg?v=1475719793
)
)
I need to merge array like this
Array
(
[0] => Array
(
[sku] => h-eldora
[name] =>
[image1] => s/files/1/1282/4221/products/h_eldora_02.jpg?v=1475116221
[image2] => s/files/1/1282/4221/products/20100707164858197_1_88da6866-701a-42b9-b523-5e454cbcce70.jpg?v=1475717598
[image3] => s/files/1/1282/4221/products/20100707164858197_1_88da6866-701a-42b9-b523-5e454cbcce70.jpg?v=1475717598
)
[1] => Array
(
[sku] => hl-dracy
[name] => HL DRACY
[image1] => s/files/1/1282/4221/products/h_dracy_01.jpg?v=1475115222
[image2] => s/files/1/1282/4221/products/h_dracy_02.jpg?v=1475115223
[image3] => s/files/1/1282/4221/products/20100707164858197_1_633237aa-36ec-441b-a074-03844f6a0858.jpg?v=1475719793
)
)
If any php function is there than please let me know or any code suggestion
Using simple PHP:
<?php
$arr1 = array(
0 => array(
'sku' => 'h-eldora',
'name' => 'H ELDORA',
'image' => 's/files/1/1282/4221/products/h_eldora_01.jpg?v=1476667054'
),
1 => array(
'sku' => 'h-eldora',
'name' => '',
'image' => 's/files/1/1282/4221/products/h_eldora_02.jpg?v=1475116221'
),
2 => array(
'sku' => 'h-eldora',
'name' => '',
'image' => 's/files/1/1282/4221/products/20100707164858197_1_88da6866-701a-42b9-b523-5e454cbcce70.jpg?v=1475717598'
),
3 => array(
'sku' => 'hl-dracy',
'name' => 'HL DRACY',
'image' => 's/files/1/1282/4221/products/h_dracy_01.jpg?v=1475115222'
),
4 => array(
'sku' => 'hl-dracy',
'name' => 'H ELDORA',
'image' => 's/files/1/1282/4221/products/h_dracy_02.jpg?v=1475115223'
),
5 => array(
'sku' => 'hl-dracy',
'name' => 'H ELDORA',
'image' => 's/files/1/1282/4221/products/20100707164858197_1_633237aa-36ec-441b-a074-03844f6a0858.jpg?v=1475719793'
)
);
$newArr = $imgIndex = array();
foreach($arr1 as $a){
if( !array_key_exists($a['sku'],$newArr) ){
$newArr[$a['sku']] = array(
'sku' => $a['sku'],
'name' => $a['name'],
'image1' => $a['image']
);
$imgFound[$a['sku']] = 1;
}else{
$imgFound[$a['sku']]++;
$newArr[$a['sku']]['image'.$imgFound[$a['sku']]] = $a['image'];
}
}
unset($imgFound);
echo '<pre>'; print_r($newArr); echo '</pre>';
?>
This could work for you:
$data = // your input array
$uniqueSKUs = Array();
$newArray = Array();
$currentIndex = -1;
foreach ($data as $item) {
if (!in_array($item['sku'], $uniqueSKUs)) {
$currentIndex++;
$uniqueSKUs[] = $item['sku'];
$newArray[$currentIndex] = Array(
'sku' => $item['sku'],
'name' => $item['name']
);
}
$newArray[$currentIndex]['images'][] = $item['image'];
}
echo "<pre>";
var_dump($newArray);
echo "</pre>";

Merge an array with specified values into one key

Right now, I have array sets like these:
[9] => Array
(
[sl] => 10
[upload_dt] => 2015-04-15 14:39:58
[total_files] => 3
[file_name] => logo01.png
[remarks] => qqq
[status] => pending
[download_file] => http://localhost/web/download_file21
)
[10] => Array
(
[sl] => 10
[upload_dt] => 2015-04-15 14:39:58
[total_files] => 3
[file_name] => face.jpg
[remarks] => 5645645
[status] => pending
[download_file] => http://localhost/web/download_file22
)
[11] => Array
(
[sl] => 10
[upload_dt] => 2015-04-15 14:39:58
[total_files] => 3
[file_name] => ID_11401871809904(15).pdf
[remarks] => 567567
[status] => pending
[download_file] => http://localhost/web/download_file23
)
Now, I need to merge same values in some of the indices into one arrays.
The merged array values should look like this in the end.
[9] => Array
(
[sl] => 10
[upload_dt] => 2015-04-15 14:39:58
[total_files] => 3
[file_name] => logo01.png , face.jpg, ID_11401871809904(15).pdf
[remarks] => qqq, 5645645 , 567567
[status] => pending, pending ,pending
[download_file] => http://localhost/web/download_file21,
http://localhost/web/download_file22,
http://localhost/web/download_file23
)
Now, I tried using array_merge but it didn't actually work in this case.
Solution will be like this:
<?php
$result = array();
$ar1[9] = Array
(
'sl' => 10,
'upload_dt' => '2015-04-15 14:39:58',
'total_files' => 3,
'file_name' => 'logo01.png',
'remarks' => 'qqq',
'status' => 'pending',
'download_file' => 'http://localhost/web/download_file21'
);
$ar1[10] = Array
(
'sl' => 10,
'upload_dt' => '2015-04-15 14:39:58',
'total_files' => 3,
'file_name' => 'face.jpg',
'remarks' => '5645645',
'status' => 'pending',
'download_file' => 'http://localhost/web/download_file22'
);
$ar1[11] = Array
(
'sl' => 10,
'upload_dt' => '2015-04-15 14:39:58',
'total_files' => 3,
'file_name' => 'ID_11401871809904(15).pdf',
'remarks' => 567567,
'status' => 'pending',
'download_file' => 'http://localhost/web/download_file23'
);
foreach($ar1 as $record){
$keys = array_keys($record);
foreach($keys as $key) {
if(array_key_exists($key,$result)){
$valeInKey = explode(',', $result[$key]);
if (!in_array($record[$key], $valeInKey)){
$result[$key]= $result[$key] .",".$record[$key];
}
} else{
$result[$key]= $record[$key];
}
}
}
echo"<pre>";print_r($result);exit;
?>
You're actually merging strings inside those arrays so just ditch the array_merge idea, and just use a simple loop then use the key as your basis to concatenate strings. Rough example:
$result = array();
foreach($array as $values) {
if(!isset($result[$values['sl']])) {
$result[$values['sl']] = $values; // initial
} else {
foreach(array('file_name', 'remarks', 'status', 'download_file') as $field) {
$result[$values['sl']][$field] .= ", {$values[$field]}";
}
}
}
Sample Output
array_merge won't work, because the keys would overwrite each other.
A solution would be to merge them with a the help of a foreach. Something like this:
$new = array();
foreach($arr as $key => $value) {
$new[$key] .= ", ".$value;
}
But you would have multiple entries for every single array you want to merge. If you just want to have them for a few, you have to check the key and do something accordingly.

Clean multidimensional array in php

I struggle to clean a multidimensional array. I find several Q&A:s on this topic but yet I can't get it to work.
The array $overPayments comes out (from a db call) as below.
Array (
[0] => Array (
[invoiceID] => 103080
[invoiceNumber] => 781
[faktBel] => 1500.00
[totalPayed] => 1500.00
[sumPayedOnThisJournal] => 1500.00
[totOPtoday] => 0.00
[totOPbeforeToday] => -1500.00
[totOPthisJournal] => 0.00 )
[1] => Array(
[invoiceID] => 103290
[invoiceNumber] => 7818
[faktBel] => 648.00
[totalPayed] => 893.00
[sumPayedOnThisJournal] => 893.00
[totOPtoday] => 245.00
[totOPbeforeToday] => -648.00
[totOPthisJournal] => 245.00 )
[2] => Array (
[invoiceID] => 103453
[invoiceNumber] => 202071
[faktBel] => 2250.00
[totalPayed] => 2317.00
[sumPayedOnThisJournal] => 2317.00
[totOPtoday] =>67.00
[totOPbeforeToday] => -2250.00
[totOPthisJournal] => 67.00 )
)
What I need to do is loop through the array called $overPayments containing about 200 sub arrays, and remove all "rows" (subarrays) that have $overPayment['totOPthisJournal'] <= 0. So that I end up with a either modified or new multidimensional array where the totOPthisJournal value is > 0.
I think array_filter is what you are after.
$filteredArray = array_filter($overPayments, function($value) {
return $value['totOPthisJournal'] > 0;
});
just try to unset the array index for which 'totOPthisJournal' is <=0
<?php
$array = Array ( '0' => Array ( 'invoiceID' => 103080, 'invoiceNumber' => 781, 'faktBel' => 1500.00,
'totalPayed' => 1500.00,'sumPayedOnThisJournal' => 1500.00, 'totOPtoday' => 0.00,
'totOPbeforeToday' => -1500.00, 'totOPthisJournal' => 0.00 ), '1' => Array( 'invoiceID' => 103290,
'invoiceNumber' => 7818, 'faktBel' => 648.00, 'totalPayed' => 893.00,
'sumPayedOnThisJournal' => 893.00,'totOPtoday' => 245.00, 'totOPbeforeToday' => -648.00,
'totOPthisJournal' => 245.00 ), '2' => Array ( 'invoiceID' => 103453,'invoiceNumber' => 202071,
'faktBel' => 2250.00, 'totalPayed' => 2317.00, 'sumPayedOnThisJournal' => 2317.00,
'totOPtoday' =>67.00, 'totOPbeforeToday' => -2250.00, 'totOPthisJournal' => 67.00));
foreach($array as $key=>$value){
if($array[$key]['totOPthisJournal'] <= 0){
unset($array[$key]);
}
}
print_r($array);
Put this array into a foreach loop:
foreach($overPayments as $key => $value) {
if($value['totOPthisJournal'] <= 0) {
$key = null;
}
}
This removes the overPayment where [totOPthisJournal] <= 0.
Hope this helps.

How do I make a list of specific values in a PHP multidimensional array?

I have a multidimensional array like so:
$neighborhood => array(
'the_smiths' => array(
'dad' => 'Donald',
'mom' => 'Mary',
'daughter' => 'Donna',
'son' => 'Samuel'
)
'the_acostas' => array(
'dad' => 'Diego',
'mom' => 'Marcela',
'daughter' => 'Dominga',
'son' => 'Sergio'
)
);
I would like to create another array (let's call it $array_of_moms) of all the moms in the neighborhood. Pulling them all in separately is doable, but not practical (like so):
$array_of_moms = array(
$neighborhood['the_smiths']['mom'],
$neighborhood['the_acostas']['mom'],
)
How do I create something like this:
$array_of_moms = $neighborhood['mom'];
$moms = array();
foreach($neighborhood as $family)
{
$moms[] = $family['mom'];
}
This'll iterate through each family in the array and add the mom to the new $moms array.
Using foreach, you can iterate through an array with variable indicies.
$array_of_moms = array();
foreach ($neighborhood AS $family) {
$array_of_moms[] = $family['mom']; // append mom of each family to array
}
If you can manipulate your array, you could:
<?php
$neighborhood = array(
'families' => array(
'the_smiths' => array(
'dad' => 'Donald',
'mom' => 'Mary',
'daughter' => 'Donna',
'son' => 'Samuel'
),
'the_acostas' => array(
'dad' => 'Diego',
'mom' => 'Marcela',
'daughter' => 'Dominga',
'son' => 'Sergio'
)
)
);
foreach ($neighborhood['families'] as $family => $folks) {
$neighborhood['moms'][] = $folks['mom'];
}
print_r($neighborhood);
?>
Which outputs:
Array
(
[families] => Array
(
[the_smiths] => Array
(
[dad] => Donald
[mom] => Mary
[daughter] => Donna
[son] => Samuel
)
[the_acostas] => Array
(
[dad] => Diego
[mom] => Marcela
[daughter] => Dominga
[son] => Sergio
)
)
[moms] => Array
(
[0] => Mary
[1] => Marcela
)
)
http://codepad.org/xbnj5UmV

Categories