簡體   English   中英

在 Symfony 中將實體轉換為數組

[英]Convert Entity to array in Symfony

我正在嘗試從實體獲取多維數組。

Symfony Serializer已經可以轉換為 XML、JSON、YAML 等,但不能轉換為數組。

我需要轉換,因為我想要一個干凈的var_dump 我現在的實體連接很少,完全無法閱讀。

我怎樣才能做到這一點?

顯然,可以將對象轉換為數組,如下所示:

<?php

class Foo
{
    public $bar = 'barValue';
}

$foo = new Foo();

$arrayFoo = (array) $foo;

var_dump($arrayFoo);

將產生類似的東西:

array(1) {
    ["bar"]=> string(8) "barValue"
}

如果您有私有和受保護的屬性,請參閱此鏈接: https : //ocramius.github.io/blog/fast-php-object-to-array-conversion/

從存儲庫查詢中獲取數組格式的實體

在您的 EntityRepository 中,您可以選擇您的實體並使用getArrayResult()方法指定您想要的數組。
有關更多信息,請參閱Doctrine 查詢結果格式文檔

public function findByIdThenReturnArray($id){
    $query = $this->getEntityManager()
        ->createQuery("SELECT e FROM YourOwnBundle:Entity e WHERE e.id = :id")
        ->setParameter('id', $id);
    return $query->getArrayResult();
}

如果所有這些都不適合,您應該查看有關ArrayAccess接口的 PHP 文檔。
它以這種方式檢索屬性: echo $entity['Attribute'];

您實際上可以使用內置的序列化程序將學說實體轉換為數組。 實際上,我今天剛剛寫了一篇關於此的博客文章: https : //skylar.tech/detect-doctrine-entity-changes-without/

你基本上調用了 normalize 函數,它會給你你想要的:

$entityAsArray = $this->serializer->normalize($entity, null);

我建議查看我的帖子以獲取有關某些怪癖的更多信息,但這應該完全符合您的要求,無需任何額外的依賴項或處理私有/受保護的字段。

我遇到了同樣的問題並嘗試了其他 2 個答案。 兩者都不是很順利。

  • $object = (array) $object; 在我的鍵名中添加了很多額外的文本。
  • 序列化程序沒有使用我的active屬性,因為它沒有is在它前面並且是一個boolean 它還改變了我的數據的順序和數據本身。

所以我在我的實體中創建了一個新函數:

/**
 * Converts and returns current user object to an array.
 * 
 * @param $ignores | requires to be an array with string values matching the user object its private property names.
 */
public function convertToArray(array $ignores = [])
{
    $user = [
        'id' => $this->id,
        'username' => $this->username,
        'roles' => $this->roles,
        'password' => $this->password,
        'email' => $this->email,
        'amount_of_contracts' => $this->amount_of_contracts,
        'contract_start_date' => $this->contract_start_date,
        'contract_end_date' => $this->contract_end_date,
        'contract_hours' => $this->contract_hours,
        'holiday_hours' => $this->holiday_hours,
        'created_at' => $this->created_at,
        'created_by' => $this->created_by,
        'active' => $this->active,
    ];

    // Remove key/value if its in the ignores list.
    for ($i = 0; $i < count($ignores); $i++) { 
        if (array_key_exists($ignores[$i], $user)) {
            unset($user[$ignores[$i]]);
        }
    }

    return $user;
}

我基本上將所有屬性添加到新的$user數組中,並創建了一個額外的$ignores變量,以確保可以忽略屬性(以防您不需要所有屬性)。

您可以在控制器中使用它,如下所示:

$user = new User();
// Set user data...

// ID and password are being ignored.
$user = $user->convertToArray(["id", "password"]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM