gpt4 book ai didi

php - 如何构建一个将通过多种方法更新的数组

转载 作者:搜寻专家 更新时间:2023-10-31 21:27:30 25 4
gpt4 key购买 nike

我必须检查元素 ID 是否重复,如果重复则用“-1”更新它。

//get all elements and loop through each element
public function main(){
$products = $this->getProducts();
foreach($products as $product){
$formatted_products = $this->processProducts($product);
}
}
public function processProducts($product){

//builds a csv with product data
'id' => $this->duplicateSkus($product->getSku());

if($product->getTypeId() == "configurable"){
$csv = $this->getVariants($csv, $product);
}
}

public function getVariants($csv, $product){
'id' => $this->duplicateSkus($childProduct->getSku())
}

//my main method where I check if ids are unique
public function duplicateSkus($product_sku){
if(in_array($product_sku, $products_sku)){
$product_sku = $product_sku."-1";
}
$products_sku[] = $product_sku;
return $product_sku;

}

我的问题是构建一个包含所有 ID 的数组 $products_sku 并检查每个 ID。

谢谢!

最佳答案

如果您想要一个可以在整个类中使用的数组,请为其创建一个属性:

private $array = array(); // Set up an array for this class only

然后你可以初始化它:

public function __construct()
{
$this->array = $this->AssignData; // Initialise the array of data
}

/**
* Assigner for the private $this->array
*/
private function AssignData()
{
$this->array = ["one"=>1, "two"=>2, "three"=>3, "four"=>4, "five"=>5, "six"=>6, "seven"=>7, "eight"=>8];
}

然后你就可以在你的类里面使用它了:

public function PrintArray()
{
if (array_key_exists("four", $this->array))
{
print $this->array["four"];
}
}

总的来说:

class Foo
{
private $array = array(); // Set up an array for this class only

public function __construct()
{
$this->array = $this->AsignData; // Initialise the array of data
}

/**
* Assigner for the private $this->array
*/
private function AsignData()
{
$this->array = ["one"=>1, "two"=>2, "three"=>3, "four"=>4, "five"=>5, "six"=>6, "seven"=>7, "eight"=>8];
}

public function PrintArray()
{
if (array_key_exists("four", $this->array)) //Check the array key exists
{
print $this->array["four"];
}
}
}

编辑

array_key_exists 添加了检查功能

public function CheckKeyExists($key, $search)
{
if (array_key_exists($key, $search))
return true;
else
return false;
}

关于php - 如何构建一个将通过多种方法更新的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34039779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com