从php数组获取字符串输出

时间:2016-05-31 09:23:45

标签: php arrays

我有以下数组,

    Array
    (
     [1] => Array
      (
        [0] => Array
            (
                [location] => X33
                [usernumber] => 1
                [order] => XX
                [part_number] => Hi
            )

        [1] => Array
            (
                [location] => X33
                [usernumber] => 1
                [order] => YY
                [part_number] => 68730
            )

      )

我希望输出字符串如下所示回显,

'Hello ur oder - XX, YY, part number-Hi, 68730'

如何实现此输出?我正在考虑运行foreach循环,但不确定如何将其转换为字符串?

提前致谢,

5 个答案:

答案 0 :(得分:4)

运行foreachloop和concat

$orderNumber = '';
$partnumber = '';
foreach ($yourArray as $array) {
    if ($orderNumber !="") {
        $orderNumber.=",";
    }
    $orderNumber.= $array['order'];
    if ($partNumber !="") {
        $partNumber.=",";
    }
    $partNumber.= $array['part_number'];
}
echo "Hello ur order - ".$orderNumber." part number-". $partNumber;

答案 1 :(得分:0)

您必须帮助此代码:

<?php
    $array = [
        [
            [
                'order'       => 1,
                'part_number' => 1
            ],
            [
                'order'       => 2,
                'part_number' => 2
            ]
        ]
    ];
    $orders = [];
    $partnumber = [];
    foreach($array as $v) {
        foreach($v as $item) {
            $orders[] = $item['order'];
            $partnumber[] = $item['part_number'];
        }
    }
    $str = sprintf("Hello ur oder - %s, part number-%s", implode(', ', $orders), implode(', ', $partnumber));
    echo $str;

结果:

Hello ur oder - 1, 2, part number-1, 2

答案 2 :(得分:0)

这很简单:

foreach($array[1] as $item){
   echo "Hello ur order - " . $item["order"] . ", " $item["location"] . ", part number-" . $item["order"] . ", " . $item["part_number"];
}

答案 3 :(得分:0)

@Frayne Konoks解决方案是一个很好的oneliner:

他的解决方案引用已修复:)

echo 'Hello, ur order - '.implode(", ", array_column($var[1], 'order')).', '.'part number-'.implode(", ", array_column($var[1], 'part_number'))."'";

$var是你的数组。

工作示例: http://sandbox.onlinephpfunctions.com/code/c95545bdf9d9216d6c80cc06542517e596a0360a

答案 4 :(得分:0)

我稍微更改了数组结构。下面的代码会有所帮助:

$arr = array(
    array(
        'location' => 'X33',
        'usernumber' => '1',
        'order' => 'XX',
        'part_number' => 'Hi',
    ),
    array(
        'location' => 'X33',
        'usernumber' => '1',
        'order' => 'YY',
        'part_number' => '68730',
    )
);

$order = '';
$p_no = '';
foreach ($arr as $ar) {
    $order .= $ar['order'] . ',';
    $p_no .= $ar['part_number'] . ',';
}

$order = rtrim($order, ',');
$p_no = rtrim($p_no, ',');
$final_str = 'Hello ur order - ' . $order . ' part number - ' . $p_no;
echo $final_str;