【问题标题】:Make string from array in php在php中从数组创建字符串
【发布时间】:2017-08-02 21:48:07
【问题描述】:

我有这个对象

[{"name":"Fressnapf","isChecked":true},{"name":"Whiskas","isChecked":true},{"name":"Purina","isChecked":true}]

我想构建一个这样的字符串:

"Fressnapf","Whiskas","Purina"

但如果 isChecked 布尔值之一是(例如这样的 false:[{"name":"Fressnapf","isChecked":true},{"name":"Whiskas","isChecked":false},{"name":"Purina","isChecked":true}]

那么字符串应该是这样的:

"Fressnapf","普瑞纳"

所以我有一个$brands 对象(上面的 json 形式),现在呢?

【问题讨论】:

  • foreach 循环遍历对象,检查isChecked 是否为真,然后创建一个字符串。

标签: php arrays json string object


【解决方案1】:
// Decode json to PHP array  json_decode(<JSON>, true) the second parameter converts to array instead of object
$arrays = json_decode('[{"name":"Fressnapf","isChecked":true},{"name":"Whiskas","isChecked":true},{"name":"Purina","isChecked":true}]', true);

// Create an array to store the output data you want
$checked_names = [];

// Loop through the arrays of properties in your JSON to find out if the value isChecked is true and if so add the name to your checked_names array
foreach ($arrays as $array) {
  if (!empty($array['isChecked'])) {
    $checked_names[] = $array['name'];    
  }
}

// Output with surrounding quotation marks.... implode will turn your array into a string with "glue" -- stuff in between the items... so you need the extra quotes on the outside as well
echo '"' . implode('", "', $checked_names) . '"';

【讨论】:

    【解决方案2】:
      // --- Decode the json array.
    
        $array = json_decode('[{"name":"Fressnapf","isChecked":false},{"name":"Whiskas","isChecked":true},{"name":"Purina","isChecked":true}]');
    
        $string = array();
    
        // ---  Loop through the array. 
        foreach($array as $item){
    
            // --- Check to see if item is checked. If it is, stick it into array $string.
            if($item->isChecked != false){
                $string[] = $item->name;
            }
        }
    
        // --- Transform $string to an actual string.
        $string = implode(', ', $string);
    
        echo $string;
    

    【讨论】:

    • 你可以把它连接到字符串的前面,加上这个; '", "' 用于 implode() 并将其连接到末尾。
    猜你喜欢
    • 2011-06-17
    • 2015-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 2012-11-26
    • 2016-03-10
    • 1970-01-01
    相关资源
    最近更新 更多