gpt4 book ai didi

laravel - 如何修复 laravel 和 chartjs 中的数组到字符串转换错误?

转载 作者:行者123 更新时间:2023-12-04 15:34:11 26 4
gpt4 key购买 nike

我想从学习表中获取男性学习总和和女性学习总和,并按省名分组显示到图表中。

错误:

 Array to string conversion (View: C:\xampp\htdocs\project\resources\views\chart\index.blade.php)

我的 Controller

 $learnings =DB::table('provinces')
->join('learning_province','provinces.id','learning_province.province_id')
->join('learnings','learnings.id','learning_province.learning_id')
->select('title',\DB::raw('sum(men_learned + women_learned) as sum'))
->groupby('title')->whereYear('provinces.created_at', $year)->get();

$title = [];
$learning= [];
foreach ($learnings as $key => $value) {
$title[$key]=$value->title;
$learning[$key]=$value->sum;
}
return view('home.home', compact('learning', 'title'));

如何在此脚本中按省名显示男女总和我的脚本

<script>
var ctx = document.getElementById('lineChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [{!!$title!!}],
datasets: [{
label: '# ',
data: [{!!$learning!!}],
backgroundColor: ["#3e95cd"],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>

最佳答案

但是,您可以使用 @json Blade 指令而不是手动调用 json_encode。 @json 指令接受与 PHP 的 json_encode 函数相同的参数。

请喜欢 laravel blade 中的 json_encode

<script>
var ctx = document.getElementById('lineChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: @json($title),
datasets: [{
label: '# ',
data: @json($learning),
backgroundColor: ["#3e95cd"],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>

关于laravel - 如何修复 laravel 和 chartjs 中的数组到字符串转换错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60294156/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com