【问题标题】:How can i select a single value in array php?如何在数组 php 中选择单个值?
【发布时间】:2016-08-25 12:14:23
【问题描述】:

由于 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),获取每次迭代的“标签”,使用函数 getTags(//string to split)将它们拆分到一个名为“$tags”的数组中,然后再次将它们迭代到获取每次迭代的值。

 //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]=> array(4) { [0]=> string(5) "Hello" [1]=> string(5) "world" [2]=> string(2 ) "im" [3]=> 字符串(7) "卡住" } }

而不是我所期待的:

字符串(5)“你好”

【问题讨论】:

  • 你能告诉我们getTags函数吗?
  • 第二个循环中有一个“死”,它会在显示第一个项目后立即停止执行。
  • @vincenth 当然,它用于调试我只想要循环的单次迭代

标签: php arrays json string


【解决方案1】:

只需在声明和 getTags 函数的使用中删除 $tags 之后的 [] 即可:

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

【讨论】:

  • 哇,谢谢老兄,那么将变量声明为数组对象是错误的吗?你能添加一个解释吗? :P 提前致谢!
  • 不完全是这样。使用$var = array(); 将变量声明为数组。声明$var[] ='test' 之类的东西会给你一个以test 作为第一个元素的数组。但是explode 函数已经返回了一个数组,因此您的getTags 函数返回了一个数组中的数组。然后,你把它放在另一个子数组中,这导致你最终在​​一个数组中拥有一个数组。我希望很清楚,我觉得我对所有这些数组有点迷失了方向;)
  • Nono,这是完美的答案,您可以看到结果如何:array(1) { [0]=> array(4) {
【解决方案2】:

使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    • 2011-04-08
    • 1970-01-01
    • 1970-01-01
    • 2011-07-08
    相关资源
    最近更新 更多