如何获取数组对象中的第0个索引键值

时间:2017-04-02 19:52:20

标签: php arrays object multidimensional-array

我在该对象中有一个数组对象 galleryImages 我喜欢json字符串,在这个galleryImages中我想要显示第一个图像值,如何才能获得唯一的第一个图像值?

  

我的阵列检查

$data=Array
(
    [dbResultgallery] => Array
        (
            [0] => stdClass Object
                (
                    [gallery_id] => 1
                    [className] => 1
                    [sectionName] => 1
                    [title] => Title 1
                    [description] => gfhfg
                    [galleryImages] => ["1.jpeg","2.jpg"]
                    [reg_on] => 2017-04-03 12:21:59
                    [created_by] => soupranjali@gmail.com
                    [school_id] => 2
                    [status] => 0
                )

            [1] => stdClass Object
                (
                    [gallery_id] => 2
                    [className] => 1
                    [sectionName] => 1
                    [title] => Title 2
                    [description] => sdfdsfsdfsdfsdf
                    [galleryImages] => ["3.jpeg","4.jpg","5.jpg"]
                    [reg_on] => 2017-04-03 12:23:37
                    [created_by] => soupranjali@gmail.com
                    [school_id] => 2
                    [status] => 0
                )

        )

)
  

现在我正在使用json_decode,请参阅下面的代码

foreach ($dbResultgallery as $gal) : 
    $role = json_decode($gal->galleryImages,true);
 endforeach;
  

现在我得到像

这样的数组格式
Array
    (
        [0] => 1.jpeg
        [1] => 2.jpg
    )

    Array
    (
        [0] => 3.jpeg
        [1] => 4.jpg
        [2] => 5.jpg
    )
  

预期结果

我只需要像 1.jpeg和3.jpeg 这样的第一个图像值,每个数组我只需要第0个键值

更新了代码

  

的var_dump(json_decode($ GAL-> galleryImages,真))

array(2) {

 [0]=>
  string(37) "6be1954c4bec91fe26fb7447fc551782.jpeg"
  [1]=>
  string(36) "153651d989591e76444c92cf037d5ac4.jpg"
}

array(3) {
  [0]=>
  string(37) "f356ceafa408e61cd1c62cfc39752b32.jpeg"
  [1]=>
  string(36) "a4fd29005696d92e0fc4cd3931454609.jpg"
  [2]=>
  string(36) "8eaaecdac1ff219192806acba7978a1b.jpg"
}

2 个答案:

答案 0 :(得分:1)

更改为:

$role = json_decode($gal->galleryImages,true)[0];

答案 1 :(得分:0)

   foreach ($dbResultgallery as $gal) : 
       if(strpos(json_decode($gal->galleryImages,true) ,"jpeg")!== false){
         echo 'found'; // do your stuff here
       $role = json_decode($gal->galleryImages[0],true);
        }
    endforeach