You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现多维数组内爆?循环获取的数组需转为指定格式字符串

Solution to Format Multidimensional Arrays into Target String

Got it, let's break down how to turn those nested arrays into the string format you need. Here's a straightforward approach using PHP's built-in functions:

Step-by-Step Explanation

  1. Extract the inner array: Each of your input arrays has a single outer element, which is the actual array of values we need to join (e.g., [[4]] → inner array is [4]).
  2. Join inner array elements with "-": Use implode('-', $innerArray) to turn each inner array into a hyphen-separated string.
  3. Collect all parts and join with spaces: Gather all the hyphenated strings, then join them with spaces to get the final output.

Code Example

Case 1: All arrays are stored in a single parent array

If you have all your target arrays in one big array, use this loop:

// Your input arrays grouped into a parent array
$inputArrays = [
    [[4]],
    [[3, 4]],
    [[1, 2, 30, 43, 65, 53, 634]]
];

$resultParts = [];

foreach ($inputArrays as $arr) {
    // Grab the inner array (the first element of the outer array)
    $innerValues = $arr[0];
    // Join inner values with "-"
    $resultParts[] = implode('-', $innerValues);
}

// Join all parts with spaces to get the final string
$finalOutput = implode(' ', $resultParts);

echo $finalOutput; // Output: 4 3-4 1-2-30-43-65-53-634

Case 2: Arrays are fetched one by one in a loop

If you're getting each array individually (e.g., from a database query loop), process them on the fly:

$resultParts = [];

// Example: First array fetched
$currentArray = [[4]];
$resultParts[] = implode('-', $currentArray[0]);

// Example: Second array fetched
$currentArray = [[3, 4]];
$resultParts[] = implode('-', $currentArray[0]);

// Example: Third array fetched
$currentArray = [[1, 2, 30, 43, 65, 53, 634]];
$resultParts[] = implode('-', $currentArray[0]);

// Repeat for subsequent arrays...

$finalOutput = implode(' ', $resultParts);
echo $finalOutput;

Safety Tip

If there's any chance your array structure might vary (e.g., outer array has no elements), add a quick check to avoid errors:

foreach ($inputArrays as $arr) {
    if (isset($arr[0]) && is_array($arr[0])) {
        $resultParts[] = implode('-', $arr[0]);
    }
}

内容的提问来源于stack exchange,提问作者MagicHat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:33:13