php help constructing part numbers - php

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>";
}
}
}
}
}
}
}
}
}
}
}
?>

Related

PHP - How do handle the creation of a hughe data array with many foreach loops?

I am currently working on a Symfony 6.1 project where I am trying to build a fairly large array in PHP 8.1. Now the principle basically works and the structure is correct. However, there are problems regarding the execution time and the required memory if the number for exceutions for each foreach loop gets higher.
In my current code, that you can see down below, I have also state the number of values for each foreach loop as a comment next to it.
My current code:
$data = array();
foreach($variantInformations as $key => $value) { //Between 1-7 values
foreach($value["sizes"] as $key2 => $value2) { //Between 1-7 values
foreach($value["colors"] as $key3 => $value3) {
if(isset($value3["printColors"])) { //Between 1*88 - 8*88 values
foreach($value3["printColors"] as $key4 => $value4) {
if(isset($value["printMotifs"])) {
foreach($value["printMotifs"] as $key5 => $value5) { //Between 100-300 values
if($value5["colorLevel"] == "1") {
if(!isset($value4["secondPrintColorId"])) {
$data[$key][$key2][$key3][$key4][$key5]["number"] = $variantInformations[$key]["number"]."-".$value2."-".$value3["bodyColor"]["id"]."-".$value4["id"]."-".$value5["id"];
$data[$key][$key2][$key3][$key4][$key5]["title"] = $variantInformations[$key]["title"]."-".$value2."-".$value3["bodyColor"]["title"]."-".$value4["title"]."-".$value5["title"];
$data[$key][$key2][$key3][$key4][$key5]["bodyColor"] = $value3["bodyColor"]["id"];
$data[$key][$key2][$key3][$key4][$key5]["printColor"] = $value4["id"];
$data[$key][$key2][$key3][$key4][$key5]["printMotif"] = $value5["id"];
$data[$key][$key2][$key3][$key4][$key5]["article"] = $this->articleRepository->findOneBy(["number" => $variantInformations[$key]["number"]]);
$data[$key][$key2][$key3][$key4][$key5]["active"] = 0;
$data[$key][$key2][$key3][$key4][$key5]["size"] = $value2;
$data[$key][$key2][$key3][$key4][$key5]["stock"] = "no";
$data[$key][$key2][$key3][$key4][$key5]["assortment"][] = $value["assortment"][0];
$data[$key][$key2][$key3][$key4][$key5]["printMotifStatus"] = $value5["status"];
}
}
elseif ($value5["colorLevel"] == "2") {
if(isset($value4["secondPrintColorId"])) {
$data[$key][$key2][$key3][$key4][$key5]["number"] = $variantInformations[$key]["number"]."-".$value2."-".$value3["bodyColor"]["id"]."-".$value4["id"]."-".$value4["secondPrintColorId"]."-".$value5["id"];
$data[$key][$key2][$key3][$key4][$key5]["title"] = $variantInformations[$key]["title"]."-".$value2."-".$value3["bodyColor"]["title"]."-".$value4["title"]."-".$value4["secondPrintColorTitle"]."-".$value5["title"];
$data[$key][$key2][$key3][$key4][$key5]["bodyColor"] = $value3["bodyColor"]["id"];
$data[$key][$key2][$key3][$key4][$key5]["printColor"] = $value4["id"];
$data[$key][$key2][$key3][$key4][$key5]["secondPrintColorId"] = $value4["secondPrintColorId"];
$data[$key][$key2][$key3][$key4][$key5]["printMotif"] = $value5["id"];
$data[$key][$key2][$key3][$key4][$key5]["article"] = $this->articleRepository->findOneBy(["number" => $variantInformations[$key]["number"]]);
$data[$key][$key2][$key3][$key4][$key5]["active"] = 0;
$data[$key][$key2][$key3][$key4][$key5]["size"] = $value2;
$data[$key][$key2][$key3][$key4][$key5]["stock"] = "no";
$data[$key][$key2][$key3][$key4][$key5]["assortment"][] = $value["assortment"][0];
$data[$key][$key2][$key3][$key4][$key5]["printMotifStatus"] = $value5["status"];
}
}
}
}
}
}
}
}
}
Currently I am thinking about how I can make this process faster and how I can optimize it or if it needs a completely different approach.
Does anyone have any ideas or suggestions?
You can reduce the number of accesses.
if (!isset($value4["secondPrintColorId"])) {
$data[$key][$key2][$key3][$key4][$key5] = [
'number' => $variantInformations[$key]["number"] . "-" . $value2 . "-" . $value3["bodyColor"]["id"] . "-" . $value4["id"] . "-" . $value5["id"],
'title' => $variantInformations[$key]["title"] . "-" . $value2 . "-" . $value3["bodyColor"]["title"] . "-" . $value4["title"] . "-" . $value5["title"],
'bodyColor' => $value3["bodyColor"]["id"],
'printColor' => $value4["id"],
'printModel' => $value5["id"],
'article' => $this->articleRepository->findOneBy(["number" => $variantInformations[$key]["number"]]),
'active' => 0,
'size' => $value2,
'stock' => 'no',
'assortment' => [$value["assortment"][0]],
'printMotifStatus' => $value5["status"],
];
}
Also you are calling the DB with findOneBy() in the loop. This is slow. You could either cache them when used multiple times or do one query instead of hundreds/thousands.

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);

Read Multiple Values from Array in Foreach Loop 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

PHP — How to determine number of parents of a child array?

I'm not so strong with arrays but I need to determine how to count the number of parents a child array has in order to determine the indenting to display it as an option in a SELECT.
So, if I have this array:
array(
'World'=>array(
'North America'=>array(
'Canada'=>array(
'City'=>'Toronto'
)
)
)
);
How would I go about determining how many parents 'City' has in order to translate that into the number of spaces I want to use as an indent?
Thanks for any help.
EDIT: Let's see if I can explain myself better:
I have this code I'm using to build the OPTIONS list for a SELECT:
function toOptions($array) {
foreach ($array as $key=>$value) {
$html .= "<option value=\"" . $key . "\" >";
$html .= $value['title'];
$html .= "</option>";
if (array_key_exists('children', $value)) {
$html .= toOptions($value['children']);
}
}
return $html;
}
print toOptions($list);
So, I'm trying to determine how to get the number of parents in order to add spaces before the title in this line:
$html .= $value['title'];
Like:
$html .= " " . $value['title'];
But, I'm not sure how to figure out how many spaces to add.
Hopefully this is more clear.
Thanks for any help so far.
$x = array(
'World'=>array(
'North America'=>array(
'Canada'=>array(
'City'=>'Toronto'
)
)
)
);
// This function do something with the key you've found in the array
function visit($name, $depth)
{
echo $name . ' has ' . $depth . ' parents.';
}
// This function visits all the contents aff $array
function find_recursive($array, $depth = 0)
{
if (is_array($array)) {
foreach ($array as $k => $value) {
visit($k, $depth + 1);
find_recursive($array, $depth + 1);
}
}
}
For visiting:
find_recursive($x);
Well. Off the top what you are dealing with is a multi dimensional array.
You could run a count w/ foreach on each level of the array, and use the count number returned +1 for each level the foreach loops through.
I'm not sure if this answers your question, but I am trying to see exactly what it is you are trying to achieve.
As you are already using a recursive function to display that data, you can just extend your function. There is no need to traverse the array more often than one time:
function getWhitespaces($count) {
$result = '';
while($count--) {
$result .= '$nbsp;';
}
return $result;
}
function toOptions($array, $level=0) {
foreach ($array as $key=>$value) {
$html .= "<option value=\"" . $key . "\" >";
$html .= getWhitespaces($level) + $value['title'];
$html .= "</option>";
if (array_key_exists('children', $value)) {
$html .= toOptions($value['children'], $level + 1);
}
}
return $html;
}
print toOptions($list);
Try the following.. Your solution screams for recursion in my mind. Its a bit ugly but it seems to work
$totraverse = array(
'Moon' => array(
'Dark Side' => "Death Valley"
),
'Halley Commet' => "Solar System",
'World' => array(
'North America' => array(
'Canada' => array(
'City' => 'Toronto'
)
), 'South America' => array(
'Argentina' => array(
'City' => 'Toronto'
)
)
)
);
function traverse($totraverse_, $path="", $count=0) {
global $array;
// echo count($totraverse_) . " count\n";
if (!is_array($totraverse_)) {
echo "returning $path and $key\n";
return array($path, $count);
} else {
foreach ($totraverse_ as $key => $val) {
echo "assting $path and $key\n";
$result = traverse($val, $path . "/" . $key, $count + 1);
if($result){
$array[]=$result;
}
}
}
echo false;
}
$array = array();
traverse($totraverse);
foreach($array as $item){
echo "{$item[0]}--->{$item[1]}\n";
}

PHP: get current array key?

$array = (
array('1231415'=>array('foo'=>'bar', 'test'=> 1)),
array('32434'=>array('foo'=>'bar', 'test'=> '0')),
array('123244'=>array('foo'=>'bar', 'test'=> 0)),
array('193928'=>array('foo'=>'bar', 'test'=> 1))
);
I have an array that has (many) random keys, the ID number. I need to test each array within if 'test' = 1, and so I made a foreach loop.
foreach ($array as $sub) {
if ($sub['test'] == '1' ) {
echo 'User: ' . $sub . ' has test = 1';
}
}
This works, but it returns 'User: Array has test = 1'
How on earth to I get which ID number, (that random number) has test=1 in it?
I tried doing $array as $sub=>$value, but for some reason it just makes the foreach not work. Thank you!
Use this foreach syntax instead:
foreach ($array as $key => $sub) {
if ($sub['test'] == '1' ) {
echo 'User: ' . $key . ' has test = 1';
}
}
This assumes that the data is in the form:
$array = array(
'1234' => array('test' => 1),
'5678' => array('test' => 2)
);
If you need to keep your data as it is now, you'll need to use something more like:
foreach ($array as $item) {
list($key, $info) = $item;
if ($info['test'] == 1) {
echo 'User: ' . $key . ' has test = 1';
}
}
There are 2 problems with your code.
1) Your array declaration is slightly messed up. Try this:
$array = array(
'1231415'=>array('foo'=>'bar', 'test'=> 1),
'32434'=>array('foo'=>'bar', 'test'=> 0),
'123244'=>array('foo'=>'bar', 'test'=> 0),
'193928'=>array('foo'=>'bar', 'test'=> 1)
);
2) In your foreach, you're losing the id key. Try this:
foreach ($array as $id => $sub) {
if ($sub['test'] == 1) {
echo "User: " . $id . " has test = 1\n";
}
}
In my test the above outputs:
User: 1231415 has test = 1
User: 193928 has test = 1

Categories