Pushing key value pairs into an array from an SQL query - php

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),
);
}

Related

CSGO Steam API ~ How to fetch both tradeable and non-tradeable items into array

My code is here:
case 'get_inv':
if(!$user) exit(json_encode(array('success'=>false, 'error'=>'You must login to access the deposit.')));
if((file_exists('cache/'.$user['steamid'].'.txt')) && (!isset($_GET['nocache']))) {
$array = file_get_contents('cache/'.$user['steamid'].'.txt');
$array = unserialize($array);
$array['fromcache'] = true;
if(isset($_COOKIE['tid'])) {
$sql = $db->query('SELECT * FROM `trades` WHERE `id` = '.$db->quote($_COOKIE['tid']).' AND `status` = 0');
if($sql->rowCount() != 0) {
$row = $sql->fetch();
$array['code'] = $row['code'];
$array['amount'] = $row['summa'];
$array['tid'] = $row['id'];
$array['bot'] = "Bot #".$row['bot_id'];
} else {
setcookie("tid", "", time() - 3600, '/');
}
}
exit(json_encode($array));
}
$prices = file_get_contents('prices.txt');
$prices = json_decode($prices, true);
$inv = file_get_contents('https://steamcommunity.com/profiles/'.$user['steamid'].'/inventory/json/730/2/');
$inv = json_decode($inv, true);
if($inv['success'] != 1) {
exit(json_encode(array('error'=>'Your profile is private. Please set your inventory to public and try again.')));
}
$items = array();
foreach ($inv['rgInventory'] as $key => $value) {
$id = $value['classid'].'_'.$value['instanceid'];
$trade = $inv['rgDescriptions'][$id]['tradable'];
if(!$trade) continue;
$name = $inv['rgDescriptions'][$id]['market_hash_name'];
$price = $prices['response']['items'][$name]['value']*0.9;
$img = 'http://steamcommunity-a.akamaihd.net/economy/image/'.$inv['rgDescriptions'][$id]['icon_url'];
if((preg_match('/(Souvenir)/', $name)) || ($price < $min)) {
$price = 0;
$reject = 'Junk';
} else {
$reject = 'unknown item';
}
$items[] = array(
'assetid' => $value['id'],
'bt_price' => "0.00",
'img' => $img,
'name' => $name,
'price' => $price,
'reject' => $reject,
'sa_price' => $price,
'steamid' => $user['steamid']);
}
$array = array(
'error' => 'none',
'fromcache' => false,
'items' => $items,
'success' => true);
if(isset($_COOKIE['tid'])) {
$sql = $db->query('SELECT * FROM `trades` WHERE `id` = '.$db->quote($_COOKIE['tid']).' AND `status` = 0');
if($sql->rowCount() != 0) {
$row = $sql->fetch();
$array['code'] = $row['code'];
$array['amount'] = $row['summa'];
$array['tid'] = $row['id'];
$array['bot'] = "Bot #".$row['bot_id'];
} else {
setcookie("tid", "", time() - 3600, '/');
}
}
file_put_contents('cache/'.$user['steamid'].'.txt', serialize($array), LOCK_EX);
exit(json_encode($array));
break;
I am trying to get people steam csgo inventory and put into an array. This works perfectly. Could someone help me figure out how to add a not tradeable tag. My plan is to add the item to the array even if not tradeable. I currently have it so if the item isnt worth < $0.30 then call it junk and ignore the press when clicked on. So something like if (!tradable) then mark as "trade locked" and ignore the press. Thank you.

How to get all the results where parent is an item from an array

I have an array that consists names of parents ,I want to get all the results where any of the name is a parent.Here is my code.I am not able to get the list of names where parent is equal to the names in district array.
Here is my complete code.
<?php
$functionname = 'core_course_get_categories';
$username = array('key' => 'name', 'value' => '2016');
$params = array('criteria' => array($username));
$server_url = 'localhost/moodle' . '/webservice/rest/server.php' . '?wstoken=' . '9cdaccf3a7ad2f0f94922ccfd02559f4' . '&wsfunction=' . $functionname;
$rest_format = 'json';
require_once('curl.inc');
$curl = new curl;
$rest_format = ($rest_format == 'json') ? '&moodlewsrestformat=' . $rest_format : '';
$resp = $curl->post($server_url . $rest_format, $params);
$res = json_decode($resp);
// drupal_set_message('<pre>'. dpm($res) .'</pre>');
$district = array();
$Ctsc = array();
$School = array();
$Grade = array();
$parent = array();
foreach ($res as $r) {
$a = $r->parent;
$c = $r->name;
if ($a == 0) {
$b = $r->id;
var_export($b);
}
}
foreach ($res as $r) {
if ($r->parent == $b) {
//$dist=$r->name;
$district[] = $r->name;
}
}
$Ctsc[] = $r->description;
$School[] = $r->sortorder;
$Grade[] = $r->depth;
foreach ($res as $r) {
$q = $r->name;
if (in_array($q['parent'], $district)) {
$Ctsc[] = $q->name;
dpm($Ctsc);
}
if ($Ctsc['parent'] == $district) {
dpm($Ctsc);
}
}
Usage of in_array() is wrong.
Instead of
if(in_array($q['parent'] == $district)){ ... }
use
if(in_array($q['parent'], $district)){ ... }

How to add a value at the end of JSON

$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 );

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