Read Multiple Values from Array in Foreach Loop PHP - php
I want to get array values one by one and add into foreach dynamically
$tracker = array('1','2','3')
I am able to do it manually by creating multiple foreach below
<?php
$tracker = array( '1' );
$hashx = array( $hash );
$info = $scraper->scrape( $hashx, $tracker );
foreach ($info as $key => $value) {
$openseed = $value['seeders'];
}
$tracker = array( '2' );
$hashx = array( $hash );
$info = $scraper->scrape( $hashx, $tracker );
foreach ($info as $key => $value) {
$pirateseed = $value['seeders'];
}
$tracker = array( '3' );
$hashx = array( $hash );
$info = $scraper->scrape( $hashx, $tracker );
foreach ($info as $key => $value) {
$rarbgseed = $value['seeders'];
}
?>
But I want to add all array values to foreach dynamically at once instead of creating one by one manually
<?php
$tracker = array('1','2','3');
$hashx = array( $hash );
$info = $scraper->scrape( $hashx, $tracker );
foreach ($info as $key => $value) {
$openseed = $value['seeders'];
}
?>
The above code read only first array value and i want to read all array values and store the results separately and then calculate the total number of generated result by using array_sum() like this below
$totalseed = array($pirateseed,$openseed,$rarbgseed);
echo 'Total <font color="green">Seeders:</font> '. array_sum($totalseed). '<br />';
Any help will be appreciated thanks
var tracker = [1,2,3];
var tracker_counts = [];
for( let i in tracker ) {
// scrape
tracker_counts[i] = parseInt(Math.random() * 10); // put your $value['seeders'] here
}
console.log( "Tracker seeders individually: " + tracker_counts.join(',') );
console.log( "Seeders in total: " + tracker_counts.reduce((c,v) => c+=v ) ); // use array_sum in php
As PHP
<?php
$tracker = [1,2,3];
$tracker_counts = [];
foreach( $tracker as $k => $v ) {
// scrape of $v
$tracker_counts[$k] = rand(1,9); // put your $value['seeders'] here
}
echo "Tracker seeders individually: " . implode( ', ', $tracker_counts);
echo "\n";
echo "Seeders in total: " . array_sum( $tracker_counts );
Output
Tracker seeders individually: 7, 9, 6
Seeders in total: 22
I have figured it out by the help of Andreas and Pilan so I am posting the final working solution in case of anybody else looking for it
<?php
$ftracker = array('udp://tracker.torrent.eu.org:451/announce', 'http://tracker.tfile.co:80/announce', 'http://retracker.spb.ru:80/announce', 'udp://open.demonii.si:1337/announce');
$hashx = array( $hash );
$info = $scraper->scrape( $hashx, $ftracker );
$openseed = [];
foreach($ftracker as $track){
$hashx = array( $hash );
$info = $scraper->scrape( $hashx, $track );
foreach ($info as $key => $value) {
$openseed[] = $value['seeders'];
}
}
echo 'Seed for Each Tracker Separately'.implode( ', ', $openseed);
echo 'Total Seed for All Trackers'. array_sum( $openseed );
?>
Thanks to Andreas and Pilan
Related
How to dynamically fill key and value in an associative array using for loop in PHP
$main= array( "data"=>array( "userid"=>"1", "$str", "acc_id"=>"10", "fi"=>"3" ), "next"=>"4" ); Here i added "value1"=>"$row->field1", "value2"=>"$row->field2", "value3"=>"$row->field3", "value4"=>"$row->field4" using $str Dynamically with the help of for loop because it is dynamic not fixed. I want to make this array like the below, so it can work and print correct output - It's my desired output(I want this array like this to be working) array( "data"=>array( "userid"=>"$row->uid", "value1"=>"$row->field1", "value2"=>"$row->field2", "value3"=>"$row->field3", "value4"=>"$row->field4", "acc_id"=>"$acc_id", "tloop"=>"$timeloopc" ), "next"=>"$next" ); Output is - But array taking the value of $str as string and when i print thisit shows output - Array ( [data] => Array ( [user1] => 1 [0] => "value1"=>"$row->field1", "value2"=>"$row->field2", "value3"=>"$row->field3", "value4"=>"$row->field4", "value5"=>"$row->field5" [user2] => 2 [fi] => 3 ) [next] => 4 ) The Above output is issue... Here array processing some key and value but not processing $str value... it's taking it as sting. It's now processing the $str values as string from "value1" and "field1"..to..4 Help me to dynamically fill key and value in an associative array using for loop. In the array "value1 and field1" - here numbers are dynamic - "value2" and "field2"... When i am making array dynamic, it's not working like array. If i make it static it works fine. So please help me to make $str value from string to array value(object)... Here is complete code - <?php $ct = 4; $str = ''; for($cunt=1; $cunt<=$ct; $cunt++) { $valu= '"value'; $cuntc = $cunt.'"'; $rw = '"$row'; $fild= "field"; $cp = $valu.$cuntc."=>".$rw."->".$fild.$cuntc; $str .= $cp . ','; } //trim the , from last value $str = rtrim($str, ","); $main= array("data"=>array("userid"=>"1","$str","acc_id"=>"10","fi"=>"3"),"next"=>"4"); print_r($main); ?>
I don't know what exactly you want. There is a code, which build array you'd like to have: $main= array( "data"=>array( "userid"=>"1", "$str", "acc_id"=>"10", "fi"=>"3" ), "next"=>"4" ); $ct = 4; $subArray = array(); $resultArray = array(); $resultArray['data']['userid'] = '$row->uid'; for($cunt=1; $cunt<=$ct; $cunt++) { $valu= 'value'; $rw = 'row'; $fild= "field"; $resultArray['data'][$valu . $cunt] = '$' . $rw . '->' . $fild .$cunt; } $resultArray['data']['acc_id'] = '$acc_id'; $resultArray['data']['tloop'] = '$timeloopc'; $resultArray['next'] = '$next'; echo "<pre>"; var_dump($resultArray); echo "</pre>"; But if you don't need restricted key ordering, you can use something like this (it's rebuild $main array): $main= array( "data"=>array( "userid"=>"1", "$str", "acc_id"=>"10", "fi"=>"3" ), "next"=>"4" ); $fields = array(); for($cunt=1; $cunt<=$ct; $cunt++) { $valu= 'value'; $rw = 'row'; $fild= "field"; $fields[$valu . $cunt] = '$' . $rw . '->' . $fild .$cunt; } foreach ($fields as $key => $value) { $main['data'][$key] = $value; } And there is solution with functions: function generateFieldArray($keyName, $obj, $field, $rowCount) { $resultArray = array(); for($count=1; $count<=$rowCount; $count++) { $resultArray[$keyName . $count] = '$' . $obj . '->' . $field .$count; } return $resultArray; } function buildMainArray($inputArray, $keyName, $obj, $field, $rowCount) { $arrayToAdd = generateFieldArray($keyName, $obj, $field, $rowCount); foreach ($arrayToAdd as $key => $value) { $inputArray['data'][$key] = $value; } return $inputArray; } function buildMainArray2($inputArray, $keyName, $obj, $field, $rowCount) { $resultArray = array(); $resultArray['data']['userid'] = '$row->uid'; $arrayToAdd = generateFieldArray($keyName, $obj, $field, $rowCount); foreach ($arrayToAdd as $key => $value) { $resultArray['data'][$key] = $value; } $resultArray['data']['acc_id'] = '$acc_id'; $resultArray['data']['tloop'] = '$timeloopc'; $resultArray['next'] = '$next'; return $resultArray; } $main= array( "data"=>array( "userid"=>"1", "$str", "acc_id"=>"10", "fi"=>"3" ), "next"=>"4" ); $result = buildMainArray($main, 'value', 'row', 'field', 4); // or $result = buildMainArray2($main, 'value', 'row', 'field', 4);
While loop and match records in one foreach with another
Here is the code that I will be using: $wp_query = new WP_Query([ 'post_type' => 'office', 'post_status' => 'any', 'posts_per_page' => -1, ]); $offices = []; if (count($wp_query->posts) > 0) { $offices = $wp_query->posts; } $settings['started'] = time(); foreach ($offices as $office) { $key['_office_id'] = get_post_meta($office->ID, '_office_id', true); } foreach ($records as $record) { $record_key = strtoupper(str_replace(' ', '', trim($record->location_id) . trim($record->business_unit))); } $key outputs the following: Array ( [_office_id] => ATLANTAFHUSA ) Array ( [_office_id] => AUSTINFHUSA ) $record_key outputs the following: ATLANTAFHUSA AUSTINFHUSA Here is what I'm trying to achieve .. I want to create a while loop inside the records foreach that will look at the $record_key and if there is a match with $key['_office_id'] to go ahead and echo that out. What I attempted inside the $records foreach: while ($record_key == $key['_office_id']) { if ($record_key == $key['_office_id']) { echo $record_key . " has a matching record."; } else { echo $record_key . " does not have a matching record."; } }
$keys = []; // Store all office ids foreach ($offices as $office) { $keys[] = get_post_meta($office->ID, '_office_id', true); } foreach ($records as $record) { $record_key = strtoupper(str_replace(' ', '', trim($record->location_id) . trim($record->business_unit))); // Check if current `record_key` is in `$keys` array if (in_array($record_key, $keys)) { echo 'Record key is in keys'; } else { // do something else } }
make foreach into json array
I'm a little confused, and I need help. I have a foreach loop in my code below. I need to put the foreach loop into the $data = array('image' => $final_image); How can i put foreach loop in array ? Anyone can help me please. $getImages = isset($GetNewMessageU['imageid']) ? $GetNewMessageU['imageid'] : NULL; $ExploreImage = explode(",", $getImages); $CountExplodes=count($ExploreImage); foreach($ExploreImage as $a) { $newdata=$Post->Post_GetUploadChatImageID($a); if($newdata){ $final_image=$base_url."uploads/images/".$newdata['uploaded_image']; } echo $final_image; } if($GetNewMessageU){ $json = array(); $data = array( 'image' => $final_image, ); $result = json_encode( $data ); echo preg_replace('/,\s*"[^"]+":null|"[^"]+":null,?/', '', $result); }
$getImages = isset($GetNewMessageU['imageid']) ? $GetNewMessageU['imageid'] : NULL; $ExploreImage = explode(",", $getImages); $CountExplodes=count($ExploreImage); // Create an array to store final images $final_images = []; foreach($ExploreImage as $a) { $newdata=$Post->Post_GetUploadChatImageID($a); if($newdata){ $final_image=$base_url."uploads/images/".$newdata['uploaded_image']; // Save the image if its new data. $final_images[]= $final_image; } } if($GetNewMessageU){ $json = array(); $data = array( 'image' => $final_images, // We pass the final images array ); $result = json_encode( $data ); echo preg_replace('/,\s*"[^"]+":null|"[^"]+":null,?/', '', $result); }
Made things a bit more verbose. First define the array. Then in the if statement add element to the array. $getImages = isset($GetNewMessageU['imageid']) ? $GetNewMessageU['imageid'] : NULL; $ExploreImage = explode(",", $getImages); $CountExplodes=count($ExploreImage); $final_images = array(); // Define object as array foreach($ExploreImage as $a) { $newdata=$Post->Post_GetUploadChatImageID($a); if($newdata){ $final_image=$base_url."uploads/images/".$newdata['uploaded_image']; $final_images[] = array('image' => $final_image); // Will create new array item } echo $final_image; } if($GetNewMessageU){ $json = array(); $data = array( 'image' => $final_image, ); $result = json_encode( $data ); echo preg_replace('/,\s*"[^"]+":null|"[^"]+":null,?/', '', $result); }
php help constructing part numbers
I need to create a large list of part numbers from instructions for how they can be constructed. Here are two examples. APXE-N-300-025-A0-12-ET-OO APXE-N-300-050-A0-12-ET-OO Each part number is broken into segments like: 0-1-2-3-4-5-6 and some parts have dependencies where, depending on the value of prior parts, there is a restricted selection for that particular part. Here's the php I have so far. I have an array that sort of contains the pattern but I'm struggling to create the loop that outputs all the options: $parts[0] = array('APXE'); $parts[1] = array('N','P',"S"); $parts[2] = array('300','400','600','700','800','900','1G4','1G8','2G0','2G5'); $parts[3] = array( array('dependIndex'=>'2','dependVal'=>'300','values'=>array('025','050','075','150','200','250','500','1M0','1M7','3M5')), array('dependIndex'=>'2','dependVal'=>'400','values'=>array('025','050','075','150','200','250','500','1M0','1M7','3M5')), array('dependIndex'=>'2','dependVal'=>'600','values'=>array('1M7','3M5')), array('dependIndex'=>'2','dependVal'=>'700','values'=>array('200','250','500','1M0','1M7','3M5')), array('dependIndex'=>'2','dependVal'=>'800','values'=>array('075','150','200','250','500','1M0','1M7','3M5')), array('dependIndex'=>'2','dependVal'=>'900','values'=>array('025','050','075','150','200','250','500','1M0','1M7','3M5')), array('dependIndex'=>'2','dependVal'=>'1G4','values'=>array('075','150','250','500','1M0','1M7','3M5','7M0')), array('dependIndex'=>'2','dependVal'=>'1G8','values'=>array('250','500','1M0','1M7','3M5','7M0','14M')), array('dependIndex'=>'2','dependVal'=>'2G0','values'=>array('250','500','1M0','1M7','3M5','7M0','14M')), array('dependIndex'=>'2','dependVal'=>'2G5','values'=>array('250','500','1M0','1M7','3M5','7M0','14M')) ); $parts[4] = array( array('dependIndex'=>'2','dependVal'=>'300','values'=>array('A0','A1','A2')), array('dependIndex'=>'2','dependVal'=>'400','values'=>array('B0','B1','B2','C0')), array('dependIndex'=>'2','dependVal'=>'600','values'=>array('D0')), array('dependIndex'=>'2','dependVal'=>'700','values'=>array('E0')), array('dependIndex'=>'2','dependVal'=>'800','values'=>array('F0')), array('dependIndex'=>'2','dependVal'=>'900','values'=>array('G0','G2','G3','G4')), array('dependIndex'=>'2','dependVal'=>'1G4','values'=>array('H0','H1')), array('dependIndex'=>'2','dependVal'=>'1G8','values'=>array('K0')), array('dependIndex'=>'2','dependVal'=>'2G0','values'=>array('I0')), array('dependIndex'=>'2','dependVal'=>'2G5','values'=>array('J0','J1')) ); $parts[5] = array('12','1L','24','48','AC'); $parts[6] = array('ET','FC','IC','FI','NT'); $parts[7] = array('OO'); foreach($parts as $part) foreach ($part as $bit){ if(!is_array($bit) $list[] = $bit; else foreach($bit['values'] as $val) $list[] = $val; } //?? In the above 'dependIndex'=>'2','dependVal'=>'300' means that for all part numbers with '300' in the 2nd segment, the 3rd segment can have all that array's values. I'm looking for a PHP function that is flexible enough to handle it when there are varying number of segments. Also the dependencies will change. So in the above example 4 could depend on 3 and 6 could depend on 1. Can anyone say recursion? lol Any help is greatly appreciated.
I saw your plea for help on Facebook pointing to this post and decided to take a whack at this. I changed the way your dependencies are listed, but I believe this to work (despite it being a bit rushed and brute force-like). Hopefully it will give you a good place to start. /* * The following arrays should be formatted thusly: * $exclusionlist[indexOfDeterminingColumn][indexOfDependentColumn] = array( * 'ValueOfDeterminingColumn' => array('list', 'of', 'valid', 'values') * ); */ $dependencyList[3][2] = array( '300' => array('025','050','075','150','200','250','500','1M0','1M7','3M5'), '400' => array('025','050','075','150','200','250','500','1M0','1M7','3M5'), '600' => array('1M7','3M5'), '700' => array('200','250','500','1M0','1M7','3M5'), '800' => array('075','150','200','250','500','1M0','1M7','3M5'), '900' => array('025','050','075','150','200','250','500','1M0','1M7','3M5'), '1G4' => array('075','150','250','500','1M0','1M7','3M5','7M0'), '1G8' => array('250','500','1M0','1M7','3M5','7M0','14M'), '2G0' => array('250','500','1M0','1M7','3M5','7M0','14M'), '2G5' => array('250','500','1M0','1M7','3M5','7M0','14M') ); $dependencyList[4][2] = array( '300' => array('A0','A1','A2'), '400' => array('B0','B1','B2','C0'), '600' => array('D0'), '700' => array('E0'), '800' => array('F0'), '900' => array('G0','G2','G3','G4'), '1G4' => array('H0','H1'), '1G8' => array('K0'), '2G0' => array('I0'), '2G5' => array('J0','J1') ); $dependencyList[5][1] = array( 'N' => array('12'), 'P' => array('1L'), 'S' => array('24') ); // $segments contains lists of all valid values for each segment of the part number $segments[0] = array('APXE'); $segments[1] = array('N','P',"S"); $segments[2] = array('300','400','600','700','800','900','1G4','1G8','2G0','2G5'); $segments[3] = array('025','050','075','14M','150','1M0','1M7','200','250','3M5','500','7M0'); $segments[4] = array('A0','A1','A2','B0','B1','B2','C0','D0','E0','F0','G0','G2','G3','G4','H0','H1','I0','J0','J1','K0'); $segments[5] = array('12','1L','24','48','AC'); $segments[6] = array('ET','FC','IC','FI','NT'); $segments[7] = array('OO'); $partNumbers = array(); // Loop through each segment's array foreach($segments[0] as $segment0) if(!testForExclusion(${'segment'.key($dependencyList[0])}, key($dependencyList[0]), $segment0, 0, $dependencyList)) foreach($segments[1] as $segment1) if(!testForExclusion(${'segment'.key($dependencyList[1])}, key($dependencyList[1]), $segment1, 1, $dependencyList)) foreach($segments[2] as $segment2) if(!testForExclusion(${'segment'.key($dependencyList[2])}, key($dependencyList[2]), $segment2, 2, $dependencyList)) foreach($segments[3] as $segment3) if(!testForExclusion(${'segment'.key($dependencyList[3])}, key($dependencyList[3]), $segment3, 3, $dependencyList)) foreach($segments[4] as $segment4) if(!testForExclusion(${'segment'.key($dependencyList[4])}, key($dependencyList[4]), $segment4, 4, $dependencyList)) foreach($segments[5] as $segment5) if(!testForExclusion(${'segment'.key($dependencyList[5])}, key($dependencyList[5]), $segment5, 5, $dependencyList)) foreach($segments[6] as $segment6) if(!testForExclusion(${'segment'.key($dependencyList[6])}, key($dependencyList[6]), $segment6, 6, $dependencyList)) foreach($segments[7] as $segment7) if(!testForExclusion(${'segment'.key($dependencyList[7])}, key($dependencyList[7]), $segment7, 7, $dependencyList)) $partNumbers[] = $segment0.'-'.$segment1.'-'.$segment2.'-'.$segment3.'-'.$segment4.'-'.$segment5.'-'.$segment6.'-'.$segment7; echo count( $partNumbers ); echo '<p>'; echo implode('<br/>', $partNumbers); function testForExclusion($determiningValue, $determiningSegment, $testValue, $testSegment, $exclusionList){ $excluded = false; if(isset($exclusionList[$testSegment][$determiningSegment][$determiningValue])){ if(!in_array($testValue, $exclusionList[$testSegment][$determiningSegment][$determiningValue])){ $excluded = true; } } return $excluded; } EDIT: The data structure and dependency function should be able to be used for any combination of dependencies, so this solution should be expandable.
First I think it would be good to see if you can generate one part number by using array_rand() which picks one or more random entries out of an array. Later you can modify the code to use recursion or nested foreach to output all possible parts. foreach ($parts as $part) { if (!is_array($part[0])) $list[] = array_rand($part); else { $val = "UNKNOWN"; // Handle dependencies by looking back to the relevant section of // the current part number that is being generated. foreach ($part as $bit) if ($list[$bit['dependIndex']] == $bit['dependVal']) $val = array_rand($bit['values']); $list[] = $val; } } var_dump($list); Generating all possible parts is a fairly hard problem. If this is a homework question, your professor must have a lot of confidence in you!
There are 2 functions you are looking to perform. One for resolving the dependencies, and one for the number generation. Given the dependencies in the following model: $dependencies = array( '300'=>array( 0=>array('025','050','075','150','200','250','500','1M0','1M7','3M5'), 1=>array('A0','A1','A2') ), '400'=>array( 0=>array('025','050','075','150','200','250','500','1M0','1M7','3M5'), 1=>array('B0','B1','B2','C0') ), '600'=>array( 0=>array('1M7','3M5'), 1=>array('D0') ), '700'=>array( 0=>array('200','250','500','1M0','1M7','3M5'), 1=>array('E0') ), '800'=>array( 0=>array('075','150','200','250','500','1M0','1M7','3M5'), 1=>array('F0') ), '900'=>array( 0=>array('025','050','075','150','200','250','500','1M0','1M7','3M5'), 1=>array('G0','G2','G3','G4') ), '1G4'=>array( 0=>array('075','150','250','500','1M0','1M7','3M5','7M0'), 1=>array('H0','H1') ), '1G8'=>array( 0=>array('250','500','1M0','1M7','3M5','7M0','14M'), 1=>array('H0','H1') ), '2G0'=>array( 0=>array('250','500','1M0','1M7','3M5','7M0','14M'), 1=>array('I0') ), '2G5'=>array( 0=>array('250','500','1M0','1M7','3M5','7M0','14M'), 1=>array('J0','J1') ) ); you can create a function that combines positions 3, 4, and 5 into a pre-calculated string: function position3($arrays){ $retVal = array(); foreach ($arrays as $key=>$value){ foreach ($value[0] as $v1){ foreach ($value[1] as $v2){ array_push($retVal, $key . '-' . $v1 . '-' . $v2); } } } return $retVal; } With position 3 combined in all of the defined mutations, you can map the positions into an array model as follows: $parts[0] = array('APXE'); $parts[1] = array('N','P',"S"); $parts[2] = position3($dependencies); $parts[3] = array('12','1L','24','48','AC'); $parts[4] = array('ET','FC','IC','FI','NT'); $parts[5] = array('OO'); You can then call a looping function that build each permutation of your combined values (in total, 13275) with this function: function go($parts){ $total = 0; foreach ($parts[0] as $pos1){ foreach ($parts[1] as $pos2){ foreach ($parts[2] as $pos3){ foreach ($parts[3] as $pos4){ foreach ($parts[4] as $pos5){ foreach ($parts[5] as $pos6 ){ echo implode('-', [$pos1,$pos2,$pos3,$pos4,$pos5,$pos6 ])."\n"; $total++; } } } } } } echo $total; } Putting this all together will make: function position3($arrays){ $retVal = array(); foreach ($arrays as $key=>$value){ foreach ($value[0] as $v1){ foreach ($value[1] as $v2){ #echo $key . '-' . $v1 . '-' . $v2 . "\n"; array_push($retVal, $key . '-' . $v1 . '-' . $v2); } } } return $retVal; } $dependencies = array( '300'=>array( 0=>array('025','050','075','150','200','250','500','1M0','1M7','3M5'), 1=>array('A0','A1','A2') ), '400'=>array( 0=>array('025','050','075','150','200','250','500','1M0','1M7','3M5'), 1=>array('B0','B1','B2','C0') ), '600'=>array( 0=>array('1M7','3M5'), 1=>array('D0') ), '700'=>array( 0=>array('200','250','500','1M0','1M7','3M5'), 1=>array('E0') ), '800'=>array( 0=>array('075','150','200','250','500','1M0','1M7','3M5'), 1=>array('F0') ), '900'=>array( 0=>array('025','050','075','150','200','250','500','1M0','1M7','3M5'), 1=>array('G0','G2','G3','G4') ), '1G4'=>array( 0=>array('075','150','250','500','1M0','1M7','3M5','7M0'), 1=>array('H0','H1') ), '1G8'=>array( 0=>array('250','500','1M0','1M7','3M5','7M0','14M'), 1=>array('H0','H1') ), '2G0'=>array( 0=>array('250','500','1M0','1M7','3M5','7M0','14M'), 1=>array('I0') ), '2G5'=>array( 0=>array('250','500','1M0','1M7','3M5','7M0','14M'), 1=>array('J0','J1') ) ); $parts[0] = array('APXE'); $parts[1] = array('N','P',"S"); $parts[2] = position3($dependencies); $parts[3] = array('12','1L','24','48','AC'); $parts[4] = array('ET','FC','IC','FI','NT'); $parts[5] = array('OO'); function go($parts){ $total = 0; foreach ($parts[0] as $pos1){ foreach ($parts[1] as $pos2){ foreach ($parts[2] as $pos3){ foreach ($parts[3] as $pos4){ foreach ($parts[4] as $pos5){ foreach ($parts[5] as $pos6 ){ echo implode('-', [$pos1,$pos2,$pos3,$pos4,$pos5,$pos6 ])."\n"; $total++; } } } } } } echo $total; } go($parts);
I think I understand what you want here... this is a very brute-force way of dealing with it, but should work: <?php $parts[0] = array('APXE'); $parts[1] = array('N','P',"S"); $parts[2] = array('300','400','600','700','800','900','1G4','1G8','2G0','2G5'); $parts[3] = array( array('dependIndex'=>'2','dependVal'=>'300','values'=>array('025','050','075','150','200','250','500','1M0','1M7','3M5')), array('dependIndex'=>'2','dependVal'=>'400','values'=>array('025','050','075','150','200','250','500','1M0','1M7','3M5')), array('dependIndex'=>'2','dependVal'=>'600','values'=>array('1M7','3M5')), array('dependIndex'=>'2','dependVal'=>'700','values'=>array('200','250','500','1M0','1M7','3M5')), array('dependIndex'=>'2','dependVal'=>'800','values'=>array('075','150','200','250','500','1M0','1M7','3M5')), array('dependIndex'=>'2','dependVal'=>'900','values'=>array('025','050','075','150','200','250','500','1M0','1M7','3M5')), array('dependIndex'=>'2','dependVal'=>'1G4','values'=>array('075','150','250','500','1M0','1M7','3M5','7M0')), array('dependIndex'=>'2','dependVal'=>'1G8','values'=>array('250','500','1M0','1M7','3M5','7M0','14M')), array('dependIndex'=>'2','dependVal'=>'2G0','values'=>array('250','500','1M0','1M7','3M5','7M0','14M')), array('dependIndex'=>'2','dependVal'=>'2G5','values'=>array('250','500','1M0','1M7','3M5','7M0','14M')) ); $parts[4] = array( array('dependIndex'=>'2','dependVal'=>'300','values'=>array('A0','A1','A2')), array('dependIndex'=>'2','dependVal'=>'400','values'=>array('B0','B1','B2','C0')), array('dependIndex'=>'2','dependVal'=>'600','values'=>array('D0')), array('dependIndex'=>'2','dependVal'=>'700','values'=>array('E0')), array('dependIndex'=>'2','dependVal'=>'800','values'=>array('F0')), array('dependIndex'=>'2','dependVal'=>'900','values'=>array('G0','G2','G3','G4')), array('dependIndex'=>'2','dependVal'=>'1G4','values'=>array('H0','H1')), array('dependIndex'=>'2','dependVal'=>'1G8','values'=>array('K0')), array('dependIndex'=>'2','dependVal'=>'2G0','values'=>array('I0')), array('dependIndex'=>'2','dependVal'=>'2G5','values'=>array('J0','J1')) ); $parts[5] = array('12','1L','24','48','AC'); $parts[6] = array('ET','FC','IC','FI','NT'); $parts[7] = array('OO'); foreach($parts[1] as $eigth){ foreach($parts[2] as $sect){ foreach($parts[3] as $keya => $firstloop){ foreach($parts[3][$keya] as $itemone){ foreach($parts[3][$keya]['values'] as $firstselector){ foreach($parts[4] as $keyb => $secondloop){ foreach($parts[4][$keyb] as $itemtwo){ foreach($parts[4][$keyb]['values'] as $secondselector){ foreach($parts[5] as $halve){ foreach($parts[6] as $quarter){ if($sect == $parts[3][$keya]['dependVal'] && $sect == $parts[3][$keyb]['dependVal']){ echo $parts[0][0] . "-" . $eigth . "-" . $sect . "-" . $firstselector . "-" . $secondselector . "-" . $halve . "-" . $quarter . "<br>"; } } } } } } } } } } } ?>
Create array nested PHP
Hi all' I have a page into PHP where I retrieve XML data from a server and I want to store this data into an array. This is my code: foreach ($xml->DATA as $entry){ foreach ($entry->HOTEL_DATA as $entry2){ $id = (string)$entry2->attributes()->HOTEL_CODE; $hotel_array2 = array(); $hotel_array2['id'] = $entry2->ID; $hotel_array2['name'] = utf8_decode($entry2->HOTEL_NAME); $i=0; foreach($entry2->ROOM_DATA as $room){ $room_array = array(); $room_array['id'] = (string)$room->attributes()->CCHARGES_CODE; $hotel_array2['rooms'][$i] = array($room_array); $i++; } array_push($hotel_array, $hotel_array2); } } In this mode I have the array hotel_array which all hotel with rooms. The problem is that: into my XML I can have multiple hotel with same ID (the same hotel) with same information but different rooms. If I have an hotel that I have already inserted into my hotel_array I don't want to insert a new array inside it but I only want to take its rooms array and insert into the exisiting hotel. Example now my situation is that: hotel_array{ [0]{ id = 1, name = 'test' rooms{ id = 1 } } [0]{ id = 2, name = 'test2' rooms{ id = 100 } } [0]{ id = 1, name = 'test' rooms{ id = 30 } } } I'd like to have this result instead: hotel_array{ [0]{ id = 1, name = 'test' rooms{ [0]{ id = 1 } [1]{ id = 30 } } } [0]{ id = 2, name = 'test2' rooms{ id = 100 } } } How to create an array like this? Thanks
first thing is it helps to keep the hotel id as the index on hotel_array when your creating it. foreach ($xml->DATA as $entry){ foreach ($entry->HOTEL_DATA as $entry2){ $id = (string)$entry2->attributes()->HOTEL_CODE; $hotel_array2 = array(); $hotel_array2['id'] = $entry2->ID; $hotel_array2['name'] = utf8_decode($entry2->HOTEL_NAME); $i=0; foreach($entry2->ROOM_DATA as $room){ $room_array = array(); $room_array['id'] = (string)$room->attributes()->CCHARGES_CODE; $hotel_array2['rooms'][$i] = array($room_array); $i++; } if (!isset($hotel_array[$hotel_array2['id']])) { $hotel_array[$hotel_array2['id']] = $hotel_array2; } else { $hotel_array[$hotel_array2['id']]['rooms'] = array_merge($hotel_array[$hotel_array2['id']]['rooms'], $hotel_array2['rooms']); } } }
Whilst this is the similar answer to DevZer0 (+1), there is also quite a bit that can be done to simplify your workings... there is no need to use array_merge for one, or be specific about $i within your rooms array. $hotels = array(); foreach ($xml->DATA as $entry){ foreach ($entry->HOTEL_DATA as $entry2){ $id = (string) $entry2->attributes()->HOTEL_CODE; if ( empty($hotels[$id]) ) { $hotels[$id] = array( 'id' => $id, 'name' => utf8_decode($entry2->HOTEL_NAME), 'rooms' => array(), ); } foreach($entry2->ROOM_DATA as $room){ $hotels[$id]['rooms'][] = array( 'id' => (string) $room->attributes()->CCHARGES_CODE; ); } } } Just in case it helps...
And this :) $hotel_array = array(); foreach ($xml->DATA as $entry) { foreach ($entry->HOTEL_DATA as $entry2) { $hotel_code = (string) $entry2->attributes()->HOTEL_CODE; if (false === isset($hotel_array[$hotel_code])) { $hotel = array( 'id' => $entry2->ID, 'code' => $hotel_code, 'name' => utf8_decode($entry2->HOTEL_NAME) ); foreach($entry2->ROOM_DATA as $room) { $hotel['rooms'][] = array( 'id' => (string)$room->attributes()->CCHARGES_CODE, ); } $hotel_array[$hotel_code] = $hotel; } } }