du8828 2015-11-04 05:47
浏览 65
已采纳

将数组关联到两个不同的数组并加入它们

I have associative arrays like this (stored in $array):

Array
(
    [0] => Array
        (
            [one] => some text1
            [two] => some paragraph here1.
        )

    [1] => Array
        (
            [one] => some text2
            [two] => some paragraph here2.        
        )

    [2] => Array
        (
            [one] => some text3
            [two] => some paragraph here3.        
        )

    [3] => Array
        (
            [one] => some text4
            [two] => some paragraph here4.        
        )

    [4] => Array
        (
            [one] => some text5
            [two] => some paragraph here5.        
        )

)

Now, I want to store the result of them like this:

$first = 'some text1, some text2, some text3, some text4, some text5';

$second = 'some paragraph here1. some paragraph here2. some paragraph here3. some paragraph here4. some paragraph here5.';

Struggling a lot I got a solution like this:

$first= '';
$second = '';
for($i = 0; $i<count($array); $i++){
    $first .= $array[$i]['one'] . ($i == count($array) - 1 ? '': ',');
    $second .= $array[$i]['two'];
}

echo $first;
echo $second;

But I hope there's already a built-in php function which split assoc arrays into two different arrays.

  • 写回答

4条回答 默认 最新

  • dopod0901 2015-11-04 05:49
    关注

    For PHP version > 5.5. You can simply use array_column along with implode function like as

    echo $first = implode(',',array_column($your_array,'one'));
    echo $second = implode(',',array_column($your_array,'two'));
    

    For lower version you can use array_map like as

    echo $first = implode(',',array_map(function($v){ return $v['one'];} ,$your_array));
    echo $second = implode(',',array_map(function($v){ return $v['two'];},$your_array));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi