PHP - How to add two arrays with a string in between - php

I have two arrays. I want to add : in between them and add them both into another array.
$temp = json_decode($csv[$indexLoc['allowance_json']], TRUE);
$details = is_array($temp)?(array_key_exists('details', $temp)?$temp['details']:''):'';
$anytime = is_array($temp)?(array_key_exists('anytime', $temp)?$temp['anytime']:''):'';
$deals[$counter]['deal_mins'] = $details .":". $anytime;
I need that code above to work.
I have also the basic one that always works
$deals[$counter]['deal_mins'] = is_array($temp)?(array_key_exists('details', $temp)?$temp['details']:''):'';
That one works, but I need to have two arrays separated by : instead.

Are you getting any errors? Your code looks fine.
$allowance_json = '{"details":"foo", "anytime":"bar"}';
$temp = json_decode($allowance_json, TRUE);
if (is_null($temp)) throw new Exception(json_last_error());
$details = (isset($temp['details']) ? $temp['details'] : '');
$anytime = (isset($temp['anytime']) ? $temp['anytime'] : '');
echo $details . ':' . $anytime;
That output is a string. The string values you pulled out of there concatenated by a :. With the line of code below you are pushing that string back into an array. Is that what you want?
$deals[$counter]['deal_mins'] = $details . ":" . $anytime;

Related

Arrays that are in variables and displaying them By class/for loop

This is my code: Right now as you can see you are only looking the last index. the show_results for example. First of all, the $titleNamesArr it's a simple variable that contains scraped information. Also the $imageArr , $pathAarr etc.. all the way to the $details. These variables contains each one of them exactly 20 scraped data information... so what i need is someone to guide me how can i display all the variables correctly.
<?php
session_start();
require_once 'Main.php';
require_once 'crawling.php';
$titleNamesArr = $_SESSION['titleNames'];
$imageArr = $_SESSION['imageArr'];
$pathArr = $_SESSION['pathArr'];
$subtitle = $_SESSION['subtitle'];
$description = $_SESSION['descriptionCat'];
$details = $_SESSION['details'];
Ofcourse i can do it like that: But i am reapeating myself a lot, Imagine having 100 data.
$card0 =new Main($titleNamesArr[0],$imageArr[0],$pathArr[0],$subtitle[0],$description[0],$details[0]);
echo $card0->showingCards()."<br>"."<br>";
$card1 = new Main($titleNamesArr[1],$imageArr[1],$pathArr[1],$subtitle[1],$description[1],$details[1]);
echo $card1->showingCards()."<br>"."<br>";
$card2 = new Main($titleNamesArr[2],$imageArr[2],$pathArr[2],$subtitle[2],$description[2],$details[2]);
echo $card2->showingCards()."<br>"."<br>";
This is what i have tried so far. It is returning me 11 from the 20 results, of course somewhere i am wrong.
///// Showing the cards
for($i=0; $i<=count($titleNamesArr); $i++) {
$card = new Main($titleNamesArr[$i], $imageArr[$i], $pathArr[$i], $subtitle[$i], $description[$i], $details[$i]);
echo $card->showingCards() . "<br>" . "<br>";
$i++;
}
Anyone's advise ?
If you remove the unnecessary $i++; the loop will work correctly. The loop counter is already in the for statement.
You could also fix the unnecessary literal concatenation and make "<br>" . "<br>"; into "<br><br>";
Like so:
for($i=0; $i<=count($titleNamesArr); $i++) {
$card = new Main($titleNamesArr[$i], $imageArr[$i], $pathArr[$i], $subtitle[$i], $description[$i], $details[$i]);
echo $card->showingCards() . "<br><br>";
//$i++;
}

How to insert two variable value into single field in php?

code:
<?php
if(isset($_POST['add_new']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$field = $_POST['field'];
$message = $_POST['message'];
$comment1 =array($_POST['comment1'],$s_date);
$comment2 = $_POST['comment2'];
$status = $_POST['status'];
$s_date = date('Y-m-d');
$interested_in = $_POST['interested_in'];
$academic_details = $_POST['academic_details'];
$city = $_POST['city'];
$sql = "insert into enquires2(name,email,phone,field,message,comment1,comment2,status,s_date,interested_in,academic_details,city,admin_idd)values('$name','$email','$phone','$field','$message','$comment1','$comment2','$status','$s_date','$interested_in','$academic_details','$city','$admin_id')";
$result = mysqli_query($link,$sql);
if($result == true)
{
$msg .= "<p style='color:green;'>You are successfully add new enquiry</p>";
}
else
{
$msg .= "<p style='color:red;'>Error!</p>";
}
}
?>
In this code I want to pass two value in single variable i.e.
$comment1 = array($_POST['comment1'],$s_date);
which show (array) when I print query ($sql). How can I pass two value into single variable ? please help me.
Another option if you don't want to concatenate , use serialize function make an associative array and serialize it and store to db
for example :
$comment1 =serialize(array("comment"=>$_POST['comment1'],"date"=>$s_date));
and when you get form db ,just use
$data = unserialize($yourDataFromDb);
and you get your values like
$data["comment"] // Your comment
$data["date"] // your date
Simply use concatenation
$comment1 = $_POST['comment1'] . $s_date;
But if you want to parse later and keep sepration between comment and date you can use any format like
$comment1 = $_POST['comment1'] . "--date--" . $s_date;
Later you can simply use print_r (explode("--date--",$str));
Something like multivalue field.
You already record the value of $s_date in a separate "date" field, so there's no need to record it again within the comment field.
If you want to combine them for display or reporting purposes later on, then you can easily do that in the object or UI layer using simple string concatenation. I would advise you not to do this when storing the data as you're attempting - otherwise you're just duplicating the same value twice in the row for no obvious reason, as well as making it more difficult to separate what the user actually wrote from the date you inserted into it.

How to create dynamic variables from SQL results

This one should be easy and it's killing me I can't find the solution!
I have a SQL query return records from a database. The two fields I am using are $row["staff_id"] and $row["name"].
From that I want to build a dynamic variable which is something like:
$staffid_1 = "Mark Smith";
$staffid_2 = "Sally Baker";
$staffid_3 = "Peter Pan";
The varibale name is created dynamically be combining "staffid_" and $row["staff_id"] for the first part then $row["name"] for the name.
I've tried:
${$staff_id . $row["staff_id"]} = $row["name"];
echo ${$staff_id . $row["staff_id"]} . "<br>";
But no luck! Any assistance would be appreciated :)
I would think you might be best to change your query to return the first part of it, then whatever you're calling it from to concatenate it together, eg
Query:
SELECT '$staffid_' + ltrim(rtrim(cast(staff_id as varchar))) + ' = "' + name + '"'
FROM [table list]
ORDER BY ...
Then concatenate the individual rows of result set as required, with in-between as you seem to require.
Okay so in PHP you have an awesome option to use a double leveled variable which basically means this :
$$varname = $value;
This results in the fact that if you have a string variable ,
(for example $staffid = "staffid_1") that you can do the following:
$staffid = "Jasonbourne";
$$staffid = "Matt Damon";
// Will result in
$JasonBourne = "Matt Damon";
So for your example:
$name = "staffid_" . $row["staff_id"];
$$name = $row["name"];
Will result in the variable : $staff_id_1 = "Mark Smith";
To read more about double - leveled variables :
http://php.net/manual/en/language.variables.variable.php
EDIT: If you wanna loop through the rows :
foreach ($sql_result as $row) {
$name = "staffid_" . $row["staff_id"];
$$name = $row["name"];
}

php recursive search and count of a value in json

I have a json feed with 6 objects all which have objects inside of them. I have an ID of something I am trying to search and count in another object.
if (isset($_GET['steamusr'])) {
$user = $_GET['steamusr'];
$myinv = 'http://steamcommunity.com/id/'.$user.'/inventory/json/295110/1/';
$content2 = file_get_contents($myinv);
$json2 = json_decode($content2, true);
$imgurlbase = 'http://steamcommunity-a.akamaihd.net/economy/image/';
foreach($json2['rgDescriptions'] as $i){
$item = $i['market_name'];
$icon = $i['icon_url'];
$fetchdata = 'http://steamcommunity.com/market/priceoverview/?appid=295110&currency=1&market_hash_name=' . urlencode($item);
$grab = file_get_contents($fetchdata);
$id = json_decode($grab, true);
$itemid = $i['classid'];
foreach($json2->rgInventory as $i2){
if($i2->$itemid == $itemid){
$ci = 0;
$count = $ci++ ;
}
}
All the data comes from rgDescriptions first, then rgInventory has the number of objects to count within it. The item ID comes from $itemid which I then need to search rgInventory for and then count the amount of matching id's in there from the set value $itemid.
My biggest issue is rgInventory has unique objects so I am trying to do a recursive/wildcard search of matching classid's.
The json structure can be found here: http://www.jsoneditoronline.org/?url=http://steamcommunity.com/id/fuigus/inventory/json/295110/1/
I think your code is correct in essence but you're not comparing the right things.
$json = json_decode($content2);
foreach ($json["rgDescriptions"] as $item) {
$num = 0;
foreach ($json["rgInventory"] as $inventory_entry) {
if ($inventory_entry["classid"] === $item["classid"]) {
$num += 1;
}
}
// do something with $num
var_dump($item["classid"] . ": " . $num);
}
The line:
if($i2->$itemid == $itemid){
Is bad, $i2->$itemid resolves to $i2->1107865473 which doesn't exist. I think you intended $i2->classid.
Error like this happen because you're using meaningless, abstract variable names. $i, $i2 and $content2, these are meaningless. You're also mixing the terms itemid and classid, it's easy to get confused.
Also, you're mixing bracket notation and object notation. Pick one and stick to it.

Posting Data To Mysql with IDs

I have a form with some input texts. It's counted with the name + an id. Like:
megnevezes_1
megnevezes_2
My form has also a counted id tag, called tid_1 and go on.
When I post my form i made a hidden input called darab, which counts how many id's I have.
Then I do the mysql query:
for($k=1; $k=$darab; $k++){
$command = <<<HTML
UPDATE
$dbtablename_template_tetelek
SET
vamtarifa_szj = '$vamtarifa_szj_$k',
megnevezes = '$megnevezes_$k',
me_egyseg = '$me_egyseg_$k',
mennyiseg = '$mennyiseg_$k',
afa = '$afa_$k',
egyseg_ar = 'str_replace(".","",$egyseg_ar_$k)'
WHERE template_id = '$tid_$k'
HTML;
mysql_query($command,$kapcsolat) or die(mysql_error(). $command);
}
But theres something wrong with it. How to attach to my strings the $k string with _? And how to make the str replace in the query?
Try this..
for($k=1; $k=$darab; $k++){
$blah = $egyseg_ar . '_' . $k;
$replace = str_replace(".", "", $blah);
$command = <<<HTML
UPDATE
$dbtablename_template_tetelek
SET
vamtarifa_szj = '$vamtarifa_szj_$k',
megnevezes = '$megnevezes_$k',
me_egyseg = '$me_egyseg_$k',
mennyiseg = '$mennyiseg_$k',
afa = '$afa_$k',
egyseg_ar = $replace
WHERE template_id = '$tid_$k'
HTML;
mysql_query($command,$kapcsolat) or die(mysql_error(). $command);
}
You should let PHP know precisely what it needs to parse. To help it you can use curly brackets like in '{$var1}_{$var2}'
So e.g. mennyiseg = '$mennyiseg_$k' might need to be mennyiseg = '{$mennyiseg}_{$k}' if you already have a variable named $mennyiseg in your code above the loop.

Categories