简体   繁体   English

PHP - 从数组中的键获取动态值并放入列表中

[英]PHP - Get dynamic values from keys from array and put into a list

I am working on a movie review site but I am stuck at an array problem. 我正在电影评论网站上工作,但我遇到了阵列问题。 How can I get multiple values from an Array of writers? 如何从一组编写器中获取多个值?

I get a response like this from the API Array ( [0] => Array ( [nconst] => nm0604555 [name] => Chris Morgan [attr] => (written by) ) [1] => Array ( [nconst] => nm0860155 [name] => Gary Scott Thompson [attr] => (characters) ) ) 我从API Array ( [0] => Array ( [nconst] => nm0604555 [name] => Chris Morgan [attr] => (written by) ) [1] => Array ( [nconst] => nm0860155 [name] => Gary Scott Thompson [attr] => (characters) ) )得到这样的响应Array ( [0] => Array ( [nconst] => nm0604555 [name] => Chris Morgan [attr] => (written by) ) [1] => Array ( [nconst] => nm0860155 [name] => Gary Scott Thompson [attr] => (characters) ) )

I tried echo $array[0]['name']; 我试过echo $array[0]['name']; but it only gives me the first value Chris Morgan because of the [0] 但它只给了我第一个值Chris Morgan因为[0]

Also the array response keys varies depending on how many actors are in a film. 阵列响应键也取决于电影中有多少演员。

So what can I do to list the Writers in a list? 那么我该怎样做才能列出列表中的作家? Like this: Chris Morgan, Gary Scott Thompson 像这样: Chris Morgan, Gary Scott Thompson

A basic loop can handle this: 基本循环可以处理这个:

foreach ($array as $movie) {
    echo $movie['name'] . ",";
}

With my solution, you will not have a , after the last element : 使用我的解决方案,在最后一个元素之后你将没有:

 $actors= array();
    foreach ($array as $movie) {
        $actors[] = $movie['name'];
    }

    echo implode(',', $actors);

Array_walk; Array_walk;

   Array_walk($array,function($key,$val){
      echo $val['name']. ', ';
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM