在php中使用数组创建字符串

时间:2017-08-02 21:48:08

标签: php arrays json string object

我有这个对象

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

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

  

" Fressnapf""伟嘉""普瑞纳"

但是如果isChecked boolean之一是(假的,例如像这样:$brands

然后字符串应如下所示:

  

" Fressnapf""普瑞纳"

所以我有一个// Get all rows in an array (and tell file not to include the trailing new lines $rows = file($filename, FILE_IGNORE_NEW_LINES); // Remove the first element (first row) from the array array_shift($rows); // Now do what you want with the rest foreach ($rows as $lineNumber => $row) { // do something cool with the row data } 对象(上面的json形式),现在是什么?

2 个答案:

答案 0 :(得分:0)

  // --- 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;

答案 1 :(得分:0)

// 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) . '"';