如何在数组php中选择单个值?

时间:2016-08-25 12:14:23

标签: php arrays json string

由于PHP中的数组更像是哈希映射,因此只需要获取单个值而不是整个数组

我的json对象:

[{
"title": "Hello world1",
"placement": "world",
"time": "today",
"tags": "Hello world im stucked"
 },{
"title": "Hello world2",
"placement": "world2",
"time": "today2",
"tags": "Hello2 world2 im2 stucked2"
 }]

我的getTags函数:

    function getTags($string){
       $tags[] = explode(" " , $string);
       return $tags;
    }

我的代码是迭代json对象($ obj),得到"标签"每次迭代,将它们分成一个名为" $ tags"的数组。使用函数getTags(//要拆分的字符串)并再次迭代它们以获取每次迭代的值。

 //Iterate json
 for ($i = 0 ; $i < sizeof($obj) ; $i++){

    //split the tags string to array (" ")
    $tags[] = getTags($obj[$i]->tags);

    //Iterate tags array
    for($z = 0; $z < sizeof($tags); $z++) {

       //get the value of the array
       var_dump($tags[$z]).die;
     }
}

结果将是:

  

array(1){[0] =&gt; array(4){[0] =&gt; string(5)&#34;你好&#34; [1] =&GT; string(5)&#34; world&#34; [2] =&GT; string(2)&#34; im&#34; [3] =&GT;字符串(7)&#34;卡住&#34; }}

而不是我所期待的:

  

String(5)&#34; Hello&#34;

2 个答案:

答案 0 :(得分:2)

在声明和[]功能的使用中,只需删除$tags之后的getTags

$json = '[{
"title": "Hello world1",
"placement": "world",
"time": "today",
"tags": "Hello world im stucked"
 },{
"title": "Hello world2",
"placement": "world2",
"time": "today2",
"tags": "Hello2 world2 im2 stucked2"
 }]';

function getTags($string){
   $tags = explode(" " , $string);
   return $tags;
}

$obj = json_decode($json);

//Iterate json
for ($i = 0 ; $i < sizeof($obj) ; $i++){

    //split the tags string to array (" ")
    $tags = getTags$obj[$i]->tags);

    //Iterate tags array
    for($z = 0; $z < sizeof($tags); $z++) {

    //get the value of the array
    var_dump($tags[$z]).die;
 }

答案 1 :(得分:1)

使用php explode函数将字符串拆分为数组,如下所示:

$data = '[{
"title": "Hello world1",
"placement": "world",
"time": "today",
"tags": "Hello world im stucked"
 },{
"title": "Hello world2",
"placement": "world2",
"time": "today2",
"tags": "Hello2 world2 im2 stucked2"
 }]';

$dataArray = json_decode($data,true); ///return json object as associative array. 
for ($i = 0 ; $i < sizeof($dataArray) ; $i++)
{
    $tags = explode(' ',$dataArray[$i]['tags']);//split the string into array.
    for ($z = 0 ; $z < sizeof($tags) ; $z++) //loop throug tags array
    {
        echo $tags[$z];
        die; ///remove this for further excecution.
    }
} 

会给你:

Hello