【问题标题】:Can someone please tell me why this doesn't create an associative array?有人可以告诉我为什么这不会创建关联数组吗?
【发布时间】:2016-08-17 09:25:37
【问题描述】:

我正在尝试将项目添加到关联数组,这是针对 Zend 表单(选择选项),但由于某种原因,值与选项不同。

我正在使用

$thearray[$test->address1] = $test->address1; 

我希望键和值完全相同($test->address1 的值)。发生的事情是密钥编号(0,1,2,3,4 等)但值是正确的,有人知道为什么吗?

这是我的代码

$tests = json_decode($result);

$testtwo = $tests->_embedded->house ;

$thearray = array();

foreach ($testtwo  as $test) {

    $i = $test->address1;
    $thearray[$test->address1] = $test->address1;

};

然后表单就这样创建了

   $this->add(array(
     'name' => 'address',
     'type' => 'Select',
     'options' => array(
         'label' => 'Address',
         'value_options' => $thearray,
         'disable_inarray_validator' => true,
     ),
     'attributes' => array(
         'class' => 'form-control',
         'id' => 'propertyaddress',
     ),

 ));

数组的 var_dump 将是

array(365) { 
    [0]=> string(18) "1 property address" 
    [1]=> string(27) "2 another address" 
    [2]=> string(18) "3 another addresst"
    ....

$test 的 var_dump(循环内)

   object(stdClass)#271 (11) { 
        ["id"]=> string(1) "1" ["address1"]=> string(22) "1 property address" 
        ["address2"]=> NULL 
        ["town"]=> string(10) "the town" 
        ["city"]=> string(10) "The city"
        ["county"]=> string(10) "The county" ["postcode"]=> string(8) "NN11 1NN" 
        ...

$result 的 print_r 将是

{
   "_links":{
      "self":{
         "‌​href":"http:\/\/shop.‌​dev\/house?page=1"
      },
      "‌​first":{
         "href":"http:‌​\/\/shop.dev\/house"
      }      ‌​,
      "last":{
         "href":"http‌​:\/\/shop.dev\/house?‌​page=1"
      }
   },
   "_embedded"   ‌​:{
      "house":[
         {
            "id":"1",
            ‌​"address1":"1 property address",
            "address2":‌​null,
            "town":"town",
            "c‌​ity":"city",
            "county":‌​"county",
            "postcode":"‌​NN11 1NN",
            "branch":"BRANCH NAME",
            "propertytyp‌​e":"property type",
            "landlord":"L‌​andlord name",
            "_links":{
               "sel‌​f":{
                  "href":"http:\/\/‌​shop.dev\/house\/1"
               }
            }            ‌​
         }

【问题讨论】:

  • 请显示有问题的各种数组的内容
  • var_dump( $test ); 也会有所帮助。
  • 请在 $result 中使用原始 JSONString
  • 如何验证keys?在zend 启动之后或之前,因为上面的代码应该可以工作
  • 抱歉,我是stackoverflow的新手。我更新了我的问题,而不是添加评论

标签: php associative-array zend-form


【解决方案1】:

我设法通过使用解决了这个问题;

 $c = array_combine($thearray, $thearray);

然后

 'options' => array(
             'label' => 'Address',
             'value_options' => $c,
             'disable_inarray_validator' => true,
         ),

我不确定这是否是一个正确的解决方案,但它至少解决了我的问题。

谢谢大家的意见

克林特

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-18
    • 2021-11-16
    • 2020-11-30
    • 2015-07-09
    • 2020-02-21
    • 2020-10-30
    • 2010-11-08
    相关资源
    最近更新 更多