我有以下数组。我想使用数组方法而不是循环为该数组结果像[{"dietary_options":"234"},{"dietary_options":"123"}]
json_encode。
Array
(
[0] => Array
(
[dietary_options] =>
)
[1] => Array
(
[dietary_options] =>
)
[2] => Array
(
[dietary_options] =>
)
[3] => Array
(
[dietary_options] =>
)
[4] => Array
(
[dietary_options] =>234
)
[5] => Array
(
[dietary_options] => 123
)
)
答案 0 :(得分:1)
简单地使用array_filter是简单的方法
override func viewDidLoad() {
super.viewDidLoad()
var textDatas = ["aaa","bbb","cccccc","ddddddd","ee","ffffff","ggggg","hhhh","iiiiii","jjjjjj","kkkkkk","ll","mmmmm","nnnnnnnn","ooooooooo","ppppppppp","qqqqqqqqqqqq","rrrrrrrr","sssssss","ttttttttt","uuuuuuu","vvvv","wwww","xxxxxx","yyyy","zzzzzzz"]
textDatas.forEach { (textData) in
let randomIntX = Int.random(in: 10..<Int(ScreenSize.SCREEN_WIDTH-200))
let randomIntY = Int.random(in: 50..<Int(ScreenSize.SCREEN_HEIGHT-50))
let randomIntFontSize = Int.random(in: 10..<40)
let randomIntLabelRotate = Int.random(in: 1..<3)
let label = UILabel(frame: CGRect(x: randomIntX, y: randomIntY, width: 200, height: 30))
label.font = UIFont(name: FONT_AVENIR_HEAVY,
size: CGFloat(randomIntFontSize))
label.textColor = .white
label.textAlignment = .center
label.text = textData
label.sizeToFit()
if randomIntLabelRotate == 1 {
label.transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 2)
}
self.view.addSubview(label)
}
}
答案 1 :(得分:0)
尝试此代码,
$data = array(array('dietary_options'=>''),
array('dietary_options'=>'one'),
array('dietary_options'=>'two'));
$data = array_map('array_filter', $data);
$data = array_values(array_filter($data));
print_r(json_encode($data,true));
// print_r(json_encode(array_filter($data),true));
答案 2 :(得分:0)
尝试一下。它可以按您期望的格式工作而不会循环。
$array=array(
array("dietary_options"=>"234"),
array("dietary_options"=>""),
array("dietary_options"=>""),
array("dietary_options"=>"123")
);
$array_data = array_map('array_filter', $array);
$array_data = array_filter($array_data);
$array_data = array_values($array_data);
print_r(json_encode($array_data));
答案 3 :(得分:0)
请尝试以下代码。
$data = array(array("dietary_options"=>""),array("dietary_options"=>"789"),array("dietary_options"=>"123456"));
$data = array_filter(array_map('array_filter', $data));
echo json_encode(array_values($data));
答案 4 :(得分:0)
这对我来说很好,
print_r(json_encode(array_filter($myArray)));
答案 5 :(得分:0)
php array_filter不错的选择。
$data = array(
array("dietary_options" => ''),
array("dietary_options" => ''),
array("dietary_options" => ''),
array("dietary_options" => 123),
array("dietary_options" => 234),
);
return new JsonResponse(array_values(array_filter($data, function($k){
return !!$k["dietary_options"];
})));