如何构建一个将在许多方法中更新的数组

时间:2015-12-02 10:00:02

标签: php

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

<?php
$item_arr = array(1,2,3,4,5,6,7,8,9,10);

$col_cnt = 4;

$item_cnt = count($item_arr);
$row_cnt = ceil($item_cnt/$col_cnt);
$item_in_last_row = $item_cnt%$col_cnt;
$temp_cnt = $row_cnt-1;
$curr_cnt = $row_cnt;

$curr_item = 0;
for($i=0;$i<$row_cnt;$i++){
    $curr_cnt = $row_cnt;
    for($j=$i,$x=0,$k=1;$x<$col_cnt;$x++,$j+=$curr_cnt){
        if($curr_item == $item_cnt){
            break;
        }
        if($k > $item_in_last_row && $item_in_last_row != 0){
            $abc = $curr_cnt;
            $curr_cnt = $temp_cnt;
            $temp_cnt = $abc;
        }
        print $item_arr[$j]." ";
        $k++;
        $curr_item++;
    }
    print "<br>";
} 
?>

Output:

1 4 7 9
2 5 8 10
3 6

我的问题是使用所有ID构建数组//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。

谢谢!

1 个答案:

答案 0 :(得分:1)

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

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