how do i get this values using php arrays

耗尽温柔 提交于 2020-06-29 06:43:09

问题


[
 ["STRG008c0",2,0,"orange","***STRG008*#*"], 
 ["STRG009c0",3,0,"orange","***STRG009*#*"], 
 ["STRG001c0",2,0,"green","***STRG001*#*"], 
 ["STRG003c0",3,0,"green","***STRG003*#*"], 
 ["STRG002c0",4,0,"green","***STRG002*#*"]
]

How do I get the below in a loop in PHP?

***STRG008*#*
***STRG009*#*
***STRG001*#*
***STRG003*#*
***STRG002*#*

回答1:


It looks like you want the last column values as a string.

Method 1:

Collect all last values of each subarray in a new variable, say $result and implode() them later.

<?php

$array = [
     ["STRG008c0",2,0,"orange","***STRG008*#*"], 
     ["STRG009c0",3,0,"orange","***STRG009*#*"], 
     ["STRG001c0",2,0,"green","***STRG001*#*"], 
     ["STRG003c0",3,0,"green","***STRG003*#*"], 
     ["STRG002c0",4,0,"green","***STRG002*#*"]
    ];

$result = [];
foreach ($array as $subarray) {
    $result[] = end($subarray);
} 

$result = implode(",",$result);

echo $result; 

Method 2:

You can use array_column() to filter only last column values and implode() them later. This would be a one-liner.

<?php

$array = [
     ["STRG008c0",2,0,"orange","***STRG008*#*"], 
     ["STRG009c0",3,0,"orange","***STRG009*#*"], 
     ["STRG001c0",2,0,"green","***STRG001*#*"], 
     ["STRG003c0",3,0,"green","***STRG003*#*"], 
     ["STRG002c0",4,0,"green","***STRG002*#*"]
    ];


$result = implode(",", array_column($array,4));
echo $result;



回答2:


You have to iterate through an array of arrays

$a = [
["STRG008c0",2,0,"orange","***STRG008*#*"], 
["STRG009c0",3,0,"orange","***STRG009*#*"], 
["STRG001c0",2,0,"green","***STRG001*#*"], 
["STRG003c0",3,0,"green","***STRG003*#*"], 
["STRG002c0",4,0,"green","***STRG002*#*"]
];

$keys = array_keys($a);
for($i = 0; $i < count($a); $i++) {
    
    foreach($a[$keys[$i]] as $key => $value) {
        if($key == 4) 
          echo $value . "\n";
    };
}



回答3:


You have to loop through the inner array:

$array = [
     ["STRG008c0",2,0,"orange","***STRG008*#*"], 
     ["STRG009c0",3,0,"orange","***STRG009*#*"], 
     ["STRG001c0",2,0,"green","***STRG001*#*"], 
     ["STRG003c0",3,0,"green","***STRG003*#*"], 
     ["STRG002c0",4,0,"green","***STRG002*#*"]
    ];


    foreach ($array as $array_element) {
        echo $array_element[sizeOf($array_element) - 1]."\n";
    } 


来源:https://stackoverflow.com/questions/62606336/how-do-i-get-this-values-using-php-arrays

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!