[英]Merge PHP Arrays into Simple Array?
I use print_r($test)
to display arrays like this: 我用
print_r($test)
显示这样的数组:
Array
(
[0] => 123.5
)
Array
(
[0] => 123.6
)
Array
(
[0] => 121.1
)
This list goes down for at least 100 arrays, sometimes more and sometimes less. 该列表至少包含100个阵列,有时更多,有时更少。 I want to convert these arrays into a simple array like this:
我想将这些数组转换成这样的简单数组:
Array
(
[0] => 123.5
[1] => 123.6
[2] => 121.1
)
How can I achieve this? 我该如何实现? I tried using
array_merge()
, but it does not work. 我尝试使用
array_merge()
,但是它不起作用。
EDIT 编辑
This is how I get my arrays: 这是我获取数组的方式:
$i=0;
$linkObjs = $html->find('h3.r a');
foreach ($linkObjs as $linkObj) {
$title = trim($linkObj->plaintext);
$test = array($title);
print_r($test);
$i++;
}
I only used the numbers as an example; 我仅以数字为例。 I actually deal with text.
我实际上处理文本。 Sorry for this mislead, I am new at this.
对不起,这种误导,我是新来的。
您可以为此使用array_column函数,它仅返回数组的一列。
$merged = array_column($array, 0);
This should work for you: 这应该为您工作:
Just array_reduce()
your array into a one dimensional array. 只需将
array_reduce()
数组变成一维数组即可。
$result = array_reduce($arr, "array_merge", [])
EDIT: 编辑:
To get your result you have to rewrite your code a bit, so that you collect all values into one array by go throw all elements of $linkObjs
with array_map()
. 为了获得结果,您必须稍微重写代码,以便将所有值收集到一个数组中,
$linkObjs
使用array_map()
抛出$linkObjs
所有元素。
$linkObjs = $html->find('h3.r a');
$i = count($linkObjs);
$result = array_map(function($v){
return trim($v->plaintext);
}, $linkObjs);
print_r($result);
Use this code:- 使用此代码:-
<?php
$i=0;
$data=array();
$linkObjs = $html->find('h3.r a');
foreach ($linkObjs as $linkObj) {
$title = trim($linkObj->plaintext);
$data[]=title;// this line is main line ---
$test = array($title);
print_r($test);
$i++;
}
print_r($data);
?>
You can use any of following... 您可以使用以下任何一种...
$merged = array_column($test, 0);
OR
$merged = array();
foreach($test as $t){
$merged[] = $t[0];
}
print_r($merged);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.