How to add a value at the end of JSON - php

$resultado = mysqli_query("SELECT ...");
echo '[';
for ($i=0;$i<mysqli_num_rows($resultado);$i++) {
echo ($i > 0 ? ',' : '').json_encode(mysqli_fetch_object($resultado));
}
echo ']';
Need is Insert $SLUG the end of Json so it is the same object
{
tabela:valor
slug:valor
}
tried to array_push() but without success;

You have to encode final result, not each row:
$array = array();
for ($i=0;$i<mysqli_num_rows($resultado);$i++) {
$array[] = mysqli_fetch_object( $resultado );
}
$array[] = $SLUG; # <----------------
echo json_encode( $array );
Different approach:
$array = array();
for ($i=0;$i<mysqli_num_rows($resultado);$i++) {
$array[] = mysqli_fetch_object( $resultado );
}
$final = array( 'tabela' => $array(), 'slug' => $SLUG );
echo json_encode( $final );

Related

Converting data format from array of string into numbers

I have
$resultArray = $sth->fetchAll(PDO::FETCH_NUM);
json_encode($resultArray,JSON_NUMERIC_CHECK);
as :
[["0.003,445.85"],...]
and I need data like this:
[[0.003,445.85],...]
When trying:
while ($row = $sth->fetch(PDO::FETCH_NUM)) {
$resultArray[] = explode(',', $row);
}
json_encode($resultArray,JSON_NUMERIC_CHECK);
I have got:
[null, null, ...]
How to achieve target?
Assuming that this your array
$resultArray = [
["0.003,445.85"],
["0.051,500.08"]
];
$result = array();
foreach($resultArray as $str) {
$inner = array();
foreach($str as $s) {
$split = explode(',',$s);
$inner = array_map('floatval',$split);
}
array_push($result,$inner);
}
echo json_encode($result,JSON_PRETTY_PRINT);
Which result to
[
[0.003,445.85],
[0.051,500.08]
]
or if your example wrong and it's
$resultArray = [["0.003","445.85"]];
json_encode with JSON_NUMERIC_CHECK will works

How to Take data from Explode and Check if same data

I have case by equating the existing data
i Have 2 data with format like this
$data1 = "144|aku|1!!!122|dia|2"; data description "id|name|amount"
$data2 = "144|aku|1!!!211|dia|1";
there is the same data in 2 arrays, how to make the same data in the amount section can be added and unequal data will be inserted into the array
how to make the 2 arrays become like this
$data_result = "144|aku|2!!!122|dia|2!!!211|dia|1";
this my full script
$data1 = "144|aku|1!!!122|dia|2";
$data2 = "144|aku|1!!!211|dia|1";
$simpan_array = array();
$array_status = array();
// Pecah Array dari user dulu
$array_code_user = explode('!!!', $data1 );
$jumlah_item_user = count($array_code_user) - 1;
$x = 0;
// Pecah Array dari lokal
$array_cart_local = explode('!!!',$data2 );
$jumlah_cart_local = count($array_cart_local) - 1;
$j = 0;
while( $x <= $jumlah_item_user ) {
$ambil_datacart_user = explode( '|', $array_code_user[$x] );
$idproduk_user = $ambil_datacart_user[0];
$namaprod_user = $ambil_datacart_user[1];
$jumprod_user = $ambil_datacart_user[2];
$simpan_array_0 = $idproduk_user.'|'.$namaprod_user.'|'.$jumprod_user;
while( $j <= $jumlah_cart_local ) {
$ambil_datacart_lokal = explode( '|', $array_cart_local[$j] );
$idprod_lokal = $ambil_datacart_lokal[0];
$namaprod_lokal = $ambil_datacart_lokal[1];
$jumprod_lokal = $ambil_datacart_lokal[2];
$simpan_array_1 = $idprod_lokal.'|'.$namaprod_lokal.'|'.$jumprod_lokal;
//Disamakan
if( $idproduk_user == $idprod_lokal ) {
$jumtotal = $jumprod_user + $jumprod_lokal;
$simpan_array[] = $idprod_lokal.'|'.$namaprod_lokal.'|'.$jumtotal;
$array_status[] = 1;
} else {
$simpan_array[] = $simpan_array_1;
$array_status[] = 0;
}
$j++;
}
$x++;
}
$jumlah = array_sum($array_status);
$array_jadi = join("!!!",$simpan_array);
//$datakembali = $array_jadi;
if ( $jumlah == 0 ) {
$datakembali = $simpan_array_1.'!!!'.$array_jadi;
} else {
$datakembali = $array_jadi;
}
echo $datakembali;
?>
I loop the first array and call the output "result".
Then as I loop the second I see if the data exists in result array and it they do I add it to result else I create the new item.
$array1 = explode("!!!", $array1);
$array2 = explode("!!!", $array2);
Foreach($array1 as $val){
List($id, $name, $amount) = explode("|", $val);
$result[$id] = ['name' => $name, 'amount' => $amount];
}
Foreach($array2 as $val){
List($id, $name, $amount) = explode("|", $val);
If(isset($result[$id])){
$result[$id]['amount'] += $amount;
}Else{
$result[$id] = ['name' => $name, 'amount' => $amount];
}
}
https://3v4l.org/gQjTj
I did not include the conversion back to your format.
It's a cute format with all the pipes and exclamation marks but I strongly encourage you to use json_encode().
That makes a string that can easily be decoded again without home made functions.
See here https://3v4l.org/IEhsp
You can do something like:
$array1 = "144|aku|1!!!122|dia|2";
$array2 = "144|aku|1!!!211|dia|1";
//Convert the string into array by explode
$array1 = explode( '!!!', $array1 );
$array2 = explode( '!!!', $array2 );
//Merge the 2 arrays
$merged = array_merge($array1,$array2);
//Group the array using foreach
//Loop thru the array and group using the id as key
$grouped = array();
foreach( $merged as $key => $val ) {
$val = explode( '|', $val ); //Convert the string into array
if ( !isset( $grouped[ $val[0] ] ) ) $grouped[ $val[0] ] = $val; //If key does not exist, initialise the data
else $grouped[ $val[0] ][2] += $val[2]; //If key already exist, just add the third value
}
//Format the grouped array into string
foreach( $grouped as $key => $val ) {
$grouped[ $key ] = implode( '|', $val );
}
$result = implode( '!!!', $grouped );
echo $result;
This will result to:
144|aku|2!!!122|dia|2!!!211|dia|1

Pushing key value pairs into an array from an SQL query

I'm pulling data from a database, and would like to insert it into an array. I would like the array to look like
$myArray = array(
$id => array(
"title" => $title,
"description" => $description,
"tag" => $tag,
"link" => $link
)
)
Where $id is the ID pulled from the database, $title is pulled from the "title" column of the database, and so on.
I need all of this data to be connected so that I can use a template to display the information easily.
Currently this is my code:
<?php
$query = mysqli_query($db_conn, $advice);
//Arrays for the key value pairs
$pregnancyArray = array();
$postpartumArray = array();
$babyArray = array();
$toddlerArray = array();
$parentingArray = array();
//Arrays for now
$pregnancyTitleArray = array();
$pregnancyLinkArray = array();
$pregnancyDescriptionArray=array();
$pregnancyTagArray=array();
$postpartumTitleArray = array();
$postpartumLinkArray = array();
$babyTitleArray = array();
$babyLinkArray = array();
$toddlerTitleArray = array();
$toddlerLinkArray = array();
$parentingTitleArray = array();
$parentingLinkArray = array();
function createSlug($slug)
{
$LNSH = '/[^\-\s\pN\pL]+/u';
$SDH = '/[\-\s]+/';
$slug = preg_replace($LNSH, '', mb_strtolower($slug, 'UTF-8'));
$slug = preg_replace($SDH, '-', $slug);
$slug = trim($slug, '-');
return $slug;
}
while ($row = mysqli_fetch_array($query)) {
$id = $row['adviceID'];
$title = $row['title'];
$cat = $row['cat'];
$link = createSlug($title);
$description = $row['description'];
$tag = $row['tag'];
if ($cat === 'pregnancy') {
array_push($pregnancyTitleArray, $title);
array_push($pregnancyLinkArray,$link);
array_push($pregnancyDescriptionArray, $description);
if($tag){
array_push($pregnancyTagArray, $tag);
}
else {
array_push($pregnancyTagArray, "nt");
}
} elseif ($cat === 'postpartum') {
array_push($postpartumTitleArray, $title);
array_push($postpartumLinkArray,$link);
} elseif ($cat === 'baby') {
array_push($babyTitleArray, $title);
array_push($babyLinkArray,$link);
} elseif ($cat === 'toddler') {
array_push($toddlerTitleArray, $title);
array_push($toddlerLinkArray,$link);
} elseif ($cat === 'parenting') {
array_push($parentingTitleArray, $title);
array_push($parentingLinkArray,$link);
} else {
continue;
}
}
?>
<section class="content" id="pregnancy-advice">
<h2 class="heading">Pregnancy Advice</h2>
<ul class="justified-content" style="list-style-type: none;">
<?php
for($i = 0; $i < sizeof($pregnancyTitleArray) && $i <= 15; $i++){
echo "<li class=\"extra-spacing\">" . $pregnancyTitleArray[$i] . "</li>";
}
?>
<a class="more-links" href="adviceCat.php?cat=pregnancy">More -></a>
</ul>
</section>
Can you just build an array with your result set like so:
$results = [];
while ($row = mysqli_fetch_array($query)) {
$results[$row['adviceID']] = $row;
$results[$row['adviceID']]['link'] = createSlug($title);
}
If you'd only like to have certain data in your array you can build it differently:
$results = [];
while ($row = mysqli_fetch_array($query)) {
$results[$row['adviceID']] = array(
'title' => $row['title'],
'description' => $row['description'],
'tag' => $row['tag'],
'link' => createSlug($title),
);
}

Iterating over array of arrays and presenting the results

How can I access the contents of $value[$i] which is an array. No luck using foreach in the form below.
The idea is to loop through $contentArray and display one item from each sub-array on every iteration.
$addsContent = $Adds->selectAdds(10);
$sharedArticlesContent = $SharedContent->getSharedContent($topic_selected, $filter_selected);
$blogPostsContent = $BlogPosts->getRecentBlogPostsByTopic("business");
$contentArray = array(
$sharedArticlesContent,
$addsContent ,
$blogPostsContent
);
foreach($contentArray as $value)
{
if(count($value)>$maxLength)
{
$maxLength = count($value);
}
}
for($i=0; $i<$maxLength; $i++)
{
foreach($contentArray as $value)
{
if(isset($value[$i]))
{
if($value==$sharedArticlesContent){
$data = $value[$i];
foreach($sharedArticlesContent as $data){
$post_id = $data['id'];
$uploaded_by = $data['uploaded_by'];
$text = $data['text'];
$image = $data['image'];
require 'template1.php';
}
}elseif($value==$addsContent){
//template2
}else{
//template3
}
}
}
}
You're dealing with an associative array here, you can access it like that:
<?php
$addsContent = $Adds->selectAdds(10);
$sharedArticlesContent = $SharedContent->getSharedContent($topic_selected, $filter_selected);
$blogPostsContent = $BlogPosts->getRecentBlogPostsByTopic("business");
$contentArray = array(
$sharedArticlesContent,
$addsContent ,
$blogPostsContent
);
foreach($contentArray as $value)
{
if(count($value)>$maxLength)
{
$maxLength = count($value);
}
}
for($i=0; $i<$maxLength; $i++)
{
foreach($contentArray as $value)
{
if(isset($value[$i]))
{
if($value==$sharedArticlesContent)
{
$post_id = $value[$i]['id'];
$uploaded_by = $value[$i]['uploaded_by'];
$text = $value[$i]['text'];
$image = $value[$i]['image'];
require 'template1.php';
}
elseif($value==$addsContent)
{
//template2
}
else
{
//template3
}
}
}
}
You don't need the foreach. $data is an associative array, you don't need to loop through it.
if($value==$sharedArticlesContent){
$data = $value[$i];
$post_id = $data['id'];
$uploaded_by = $data['uploaded_by'];
$text = $data['text'];
$image = $data['image'];
require 'template1.php';
}

bind param count first argument

I have the following line:
$formatsArray = $_POST['formats'];
$topicsArray = $_POST['topics'];
// Converting the array into individual strings
$formats = implode(",", $formatsArray);
$topics = implode(",", $topicsArray);
// Prepare the statement
$resources = $con->prepare("SELECT * FROM resources WHERE
(format IN (?))
AND (topic IN (?))");
// Bind the statement
$resources->bind_param('ss',$formats, $topics);
The problem is that topics derived from an array where it could contain multiple string, but 's' will only recognize 1. I would want that if the topic array has 10 entries, than there would be 10s, and same for format.
I have thinking of counting the size of the array and adding an s in every iteration, but not sure how.
Any help would be appreciated.
// Count array
$formatCount = count($formatsArray);
$topicCount = count($topicsArray);
How about this then:
<?php
$con = new mysqli("localhost", "USERNAME", "PASSWORD", "DATABASE");
$formatsArray = array('a','b','c','d',);
$topicsArray = array('x','y','z',);
$sql = 'SELECT * FROM resources WHERE (format IN (FORMAT_REPLACE_ME)) AND (topic IN (TOPIC_REPLACE_ME))';
$formatsPlaceholders = makePlaceHolders($formatsArray);
$topicsPlaceholders = makePlaceHolders($topicsArray);
$sql = str_replace('FORMAT_REPLACE_ME', $formatsPlaceholders, $sql);
$sql = str_replace('TOPIC_REPLACE_ME', $topicsPlaceholders, $sql);
//error_log(print_r($sql,1).' '.__FILE__.' '.__LINE__,0);
try {
$s = $con->prepare($sql);
$vals = array_merge($formatsArray, $topicsArray);
// from http://stackoverflow.com/a/31562035/1814739
$typDfs = str_repeat( 's' , count( $vals ) );
$params = array( $typDfs );
foreach ( $vals as $k => $v ) {
${ 'varvar' . $k } = $v;
$params[] = &${ 'varvar' . $k }; # provide references
}
call_user_func_array( array( $s, 'bind_param' ) , $params );
$s->execute();
$output = array();
$res = $s->get_result();
while ($row = $res->fetch_array(MYSQLI_NUM))
{
//error_log(print_r($row,1).' '.__FILE__.' '.__LINE__,0);
$output []= array(
'id' => $row[0],
'format' => $row[1],
'topic' => $row[2],
);
}
$s->close();
sanitize_output($output);
}
catch (\Exception $e) {
error_log(print_r($e->getMessage(),1).' '.__FILE__.' '.__LINE__,0);
}
function makePlaceHolders($arr){
$ph = '';
for ($i = 1; $i <= count($arr); $i++) {
$ph .= '?,';
}
return rtrim($ph,',');
}
function sanitize_output(array &$arr, array $args=array()) {
array_walk_recursive($arr,'so',$args);
}
function so(&$v,$k,$args) {
$excludes = isset($args['excludes']) ? $args['excludes'] : array();
if (!in_array($k,$excludes)) {
$v = trim($v);
$v = (get_magic_quotes_gpc()) ? stripcslashes($v) : $v;
$v = htmlspecialchars($v);
}
}
?>
<html>
<body>
<ul>
<?php foreach($output as $k => $o) { ?>
<li><?php echo $o['id']; echo $o['format']; echo $o['topic']; ?></li>
<?php } ?>
</ul>
</body>
</html>

Categories