首页 > 解决方案 > 如何使用 php 在第三行的两个字符之间获取字符串?

问题描述

   $abc = "['Fund', 'Amount'],
    ['Seed Fund (Investor)', 50000],
    ['Loan Fund (Spartan)', 50000],
    ['Profit (Investor)', 3000],";

如何使用 php 从上面的字符串中获取“Loan Fund (Spartan)”和 50000?

使用 foreach 循环?

使用数组?

使用 $substring()?

有更好的解决方案吗?

标签: php

解决方案


因为它是一个字符串,所以你不能循环它——但你可以把它变成一个数组,然后循环它:

// Prepare the string to represent a JSON object
$abc = str_replace("'", '"', trim($abc, ','));

// Actually turn it into a string representation of a JSON object
$abc = '[['.$abc.']]';

// Turn it into an array by json_decoding it
$abc = json_decode($abc, true);

// Grab the initial data
$abc = array_pop($abc);

// Walk the data
foreach ($abc as $set) {

    if (in_array('Loan Fund (Spartan)', $set)) {

        ...
    }
}

虽然这只是为了好玩 - 首先尝试获得更有用的数据表示(数组,真正的 JSON 对象/字符串)。


推荐阅读