In PHP, I get this back:
array(1096) {
[0]=>
array(2) {
["exuid"]=>
string(36) "c056b5ce-3b0c-4494-858a-cf184b904dc3"
[0]=>
string(36) "c056b5ce-3b0c-4494-858a-cf184b904dc3"
}
[1]=>
array(2) {
["exuid"]=>
string(36) "8a6262c6-a4e0-41a4-8a47-ecaf5f79c2d5"
[0]=>
string(36) "8a6262c6-a4e0-41a4-8a47-ecaf5f79c2d5"
}
[2]=>
array(2) {
["exuid"]=>
string(36) "728cb9b6-6240-470f-87d5-706af554cd0b"
[0]=>
string(36) "728cb9b6-6240-470f-87d5-706af554cd0b"
}
[3]=>
array(2) {
["exuid"]=>
string(36) "a26d0fdd-9a9b-4611-8c41-3d2c9b012988"
[0]=>
string(36) "a26d0fdd-9a9b-4611-8c41-3d2c9b012988"
}
ETC
What I need to end up with is defining a variable that contains all the exuid returned separated by commas. Like this:
$something = 'c056b5ce-3b0c-4494-858a-cf184b904dc3', '8a6262c6-a4e0-41a4-8a47-ecaf5f79c2d5', '728cb9b6-6240-470f-87d5-706af554cd0b', 'a26d0fdd-9a9b-4611-8c41-3d2c9b012988'
I need it in this format to push into another query:
where `exuid` in ($something)
But I can't parse this correctly. If I do var dump($result) I get the array shown above. If I do var dump($result[0]['exuid']) I get the first value back (c056b5ce-3b0c-4494-858a-cf184b904dc3), but not the others. How do I parse this and format it in the way I need it?
Just extract the column and then join:
$something = "'" . implode("','", array_column($result, 'exuid')) . "'";
If you don't have PHP >= 5.5.0 then use this in place of array_column() :
array_map(function($v) { return $v['exuid']; }, $result)
Here is the PHP code:
<?php
$exuid = array();
foreach($result as $k=>$v)
{
$exuid[] = $v['exuid'];
}
$exuid_str = "'" . implode($exuid, "','") . "'";
?>
Related
Seems really easy, but I can't seem to figure it out...
I have a simple line that gets mysql results through wordpress like this:
$sql_results = $wpdb->get_results($sql_phrase);
Then I parse it as JSON and echo it: json_encode($sql_results);
However, I want to add other data before I parse it as JSON. But I'm not sure how.
$sql_results basically gets me a list of post ID's, title and category.
It looks like this in var_dump (this is just the first row):
array(1)
{
[0]=> object(stdClass)#2737 (7)
{
["ID"]=> string(4) "2700"
["post_title"]=> string(18) "The compact helmet"
["category"]=> string(5) "Other"
}
}
Now to start with something easy, I'd like all associative arrays inside the object to have the extra key-value. I tried the following but got an error:
500 Internal error.
foreach($sql_search as $key => $value)
{
$value['pic_img'] = "test";
$sql_search[$key]=$value;
}
$result=$sql_search;
$sql_results = array(1)
{
[0]=> object(stdClass)#2737 (7)
{
["ID"]=> string(4) "2700"
["post_title"]=> string(18) "The compact helmet"
["category"]=> string(5) "Other"
}
}
foreach($sql_results as $key=>$value)
{
$value->solution = 'good';
$sql_results[$key]=$value;
}
$result=$sql_results;
var_dump($result);
$test = array ( array("ID"=>"35", "name"=>"Peter", "age"=>"43"),
array("ID"=>"34", "name"=>"James", "age"=>"19"), array("ID"=>"31", "name"=>"Joe", "age"=>"40") );
foreach($test as $key=>$value)
{
$value['solution'] = 'good';
$test[$key]=$value;
}
$result=$test;
var_dump($result);
I've been trying to create an array from a mysqli query that creates a new class 'Book'. When I run this code, it returns the correct number of rows that I have in my database, but it won't display any of the values in the rows. Definitely a newb to a lot of this stuff, any help is really appreciated! Here's the code I'm running. If I just put in a pre-populated array, the code all works great. My problem is getting the values from the database into this array.
$db = new db();
$conn = $db->connect();
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
$thearray = array();
while($array_ar = mysqli_fetch_array($result)){
$thearray[] = array(
$array_ar['username'] => new Book($array_ar['username'], $array_ar['first_name'], $array_ar['last_name']),
);
}
echo 'Rows found: ' . mysqli_num_rows($result);
return $thearray;
Ok, so I var_dump($thearray); and it gives me a multidimensional array, which is why it's returning empty values. I think I need it to return an associative array? Here's what it var_dump($thearray); returns:
array(4) {
[0]=> array(1) {
["joshua"]=> object(Book)#6 (3) {
["title"]=> string(6) "joshua" ["author"]=> string(6) "Joshua" ["description"]=> string(9) "Lundquist"
}
}
[1]=> array(1) {
["matthew"]=> object(Book)#7 (3) {
["title"]=> string(7) "matthew" ["author"]=> string(4) "Matt" ["description"]=> string(3) "Alm"
}
}
[2]=> array(1) {
["roger"]=> object(Book)#8 (3) {
["title"]=> string(5) "roger" ["author"]=> string(5) "Roger" ["description"]=> string(9) "Lundquist"
}
}
[3]=> array(1) {
["norm"]=> object(Book)#9 (3) {
["title"]=> string(4) "norm" ["author"]=> string(4) "Norm" ["description"]=> string(5) "Shupe"
}
}
}
Next I thought I would take a look at what the var_dump(); for my hard-coded array looks like, and it output this (this one works):
array(3) {
["Jungle Book"]=> object(Book)#3 (3) {
["title"]=> string(11) "Jungle Book" ["author"]=> string(10) "R. Kipling" ["description"]=> string(15) "A classic book."
}
["Moonwalker"]=> object(Book)#4 (3) {
["title"]=> string(10) "Moonwalker" ["author"]=> string(9) "J. Walker" ["description"]=> string(7) "another"
}
["PHP for Dummies"]=> object(Book)#5 (3) {
["title"]=> string(15) "PHP for Dummies" ["author"]=> string(14) "Some Smart Guy" ["description"]=> string(18) "and the final one."
}
}
It makes sense to me what's happening, but I'm not sure how to fix my code. Thank you for the help!
Don't Panic's answer got me looking in the right direction. I needed to create an associative array, not a multidimensional array. At first I was accidentally creating the multidimensional array by setting $thearray equal to "array();". By removing that, it filled in the values correctly. Thanks again for the help!
$db = new db();
$conn = $db->connect();
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
$thearray = array();
while($array_ar = mysqli_fetch_array($result)){
$title = $array_ar['username'];
$author = $array_ar['username'];
$description = $array_ar['username'];
$thearray[] = $title = new Book($title, $author, $description);
}
var_dump($thearray);
echo 'Rows found: ' . mysqli_num_rows($result);
return $thearray;
I think this is the problem.
$thearray[] = array(
$array_ar['username'] => new Book(
$array_ar['username'], $array_ar['first_name'], $array_ar['last_name']),
);
It looks like the differences between what you're getting and what you want is 1) You're wrapping the input to $thearray in an extra array() layer, and 2) You won't get string keys like you have in your hard-coded array if you just add the items using [].
Try it like this instead:
// use the username as a key, since that is what it looks like you're using as the 'title'
$thearray[$array_ar['username']] = new Book(
$array_ar['username'], $array_ar['first_name'], $array_ar['last_name']);
I have the code below to check if the object is inside the array, but in_array() is always true and I end up with the exact same object inside the array multiple times.
if(!in_array($lang, $lang_array, true)){
$languages .= $lang . ", ";
$lang_array[] = $lang;
}
I end up with something like this:
array(3) {
[0]=> object(SimpleXMLElement)#389 (1) {
["#attributes"]=> array(1) {
["Code"]=> string(1) "E"
}
}
[1]=> object(SimpleXMLElement)#388 (1) {
["#attributes"]=> array(1) {
["Code"]=> string(1) "E"
}
}
[2]=> object(SimpleXMLElement)#387 (1) {
["#attributes"]=> array(1) {
["Code"]=> string(1) "E"
}
}
}
If all you're interested in is the Code attribute, why not simply store that then run the array through array_unique?
$lang_array = [];
foreach(...) {
$lang_array[] = (string) $lang['Code'];
}
$lang_array = array_unique($lang_array);
$languages = implode(', ', $lang_array);
in_array requires an array scan for each call. Better is to make use of string keys. Since the objects are convertible to strings, you can use the string value as keys if the string value is unique. Arrays work well for sets of integers or strings, with the keys as elements, since keys can't be repeated.
$langs[(string)$lang] = $lang;
...
$languages = implode(', ', $langs);
I have a php page which returns a php array as the following
array(6) {
[0]=>
array(2) {
["cityName"]=>
string(10) "Ananindeua"
[0]=>
string(10) "Ananindeua"
}
[1]=>
array(2) {
["cityName"]=>
string(8) "An�polis"
[0]=>
string(8) "An�polis"
}
[2]=>
array(2) {
["cityName"]=>
string(8) "Anderson"
[0]=>
string(8) "Anderson"
}
[3]=>
array(2) {
["cityName"]=>
string(6) "Angers"
[0]=>
string(6) "Angers"
}
[4]=>
array(2) {
["cityName"]=>
string(9) "Angoul�me"
[0]=>
string(9) "Angoul�me"
}
[5]=>
array(2) {
["cityName"]=>
string(6) "Anshan"
[0]=>
string(6) "Anshan"
}
}
I want to use this array in another page to do some ajax, and I want to encode the resulat into a JSON as the following :
{
"cityName": "Anshan",
"cityName": "Angoul�me",
"cityName": "Anderson",
"cityName": "An�polis",
"cityName": "Ananindeua"
}
but Instead I get only one value, which is the last value :
{
"cityName": "Anshan"
}
This is the code I tried :
<?php
$connexion = new PDO("mysql:host=localhost;dbname=world", 'root', 'toor');
$statement = $connexion->prepare("SELECT cityName FROM cities WHERE cityName LIKE '" . $_POST['cityName'] . "%'");
$statement->execute();
$resultats = $statement->fetchAll();
foreach($resultats as $city) {
$output[key($city)] = current($city);
}
echo json_encode($output, 128);
?>
So how can I solve this problem ?
Edit :
I tried to get only cities names, and push them into an array, when I do a var_dump() for this array this is what I get :
array(6) {
[0]=>
string(10) "Ananindeua"
[1]=>
string(8) "An�polis"
[2]=>
string(8) "Anderson"
[3]=>
string(6) "Angers"
[4]=>
string(9) "Angoul�me"
[5]=>
string(6) "Anshan"
}
But when I did a json_encode() I don't get anything, so I tried to do a var_dump(json_encode($output)); and I get this :
bool(false)
In the second time I tried to create a table manually :
$a = array("Ananindeua","Anápolis","Anderson","Angers","Angoulême","Anshan" );
and it worked.
But why the first array won't encode !
Your desired output is not valid/conceivable either as a PHP associative array or JSON because in both cases, you have duplicate keys.
You're just overwriting the cityName key with each iteration. Push to an array instead:
foreach($resultats as $city) {
$output[] = current($city);
}
echo json_encode($output, 128);
Output:
[
"Anshan",
"Angoulme",
"Anpolis"
]
Or if you want an object for each city, which is useful if you want other properties:
foreach($resultats as $city) {
$output[] = array(
'cityName' => current($city)
);
}
echo json_encode($output, 128);
Output:
[
{
"cityName" : "Anshan",
},
{
"cityName" : "Angoulme",
},
{
"cityName" : "Anpolis"
}
]
Side note: if you don't need the numerical keys from the PDO fetch call, consider using the PDO::FETCH_ASSOC fetch style, to bring back only associative keys:
$resultats = $statement->fetchAll(PDO::FETCH_ASSOC);
The json you're expecting doesn't look right. It should be:
[
{"cityName": "Anshan"},
{"cityName": "Angoul�me"},
{"cityName": "Anderson"},
{"cityName": "An�polis"},
{"cityName": "Ananindeua"}
]
and to generate this you need code like this:
foreach($resultats as $city) {
$item = new stdClass();
$item.cityName = current($city);
$output[] = item;
}
Your array's key is same (cityName), so the value getting replaced on each assignment.
use a numeric array, or another method that differentiating the key
e.g.,
foreach($resultats as $city) {
$output['cityName'][] = current($city);
}
output will be
{"cityName":
[
"Anshan",
"Angoulme",
"Anpolis"
]
}
The problem was that the table which I populate from database contains some accented characters, so the json_encode() failing.
The solution was to add charset=UTF8 in the first parameter of the PDO instance.
$connexion = new PDO("mysql:host=localhost;dbname=world;charset=UTF8", 'root', 'toor');
Could you trim all $_POST vars? because i have a very long list right now for trim each var. looks very unprofessional. i thought trim($_POST); would maybe work but it didnt :]
you can do this with array_map:
$_POST = array_map('trim', $_POST);
Works with multi-dimensional arrays
array_walk_recursive($_POST, function (&$val)
{
$val = trim($val);
});
foreach($_POST as &$p) $p = trim($p);
Quick and simple:
foreach($_POST as $key => $val)
{
$_POST[$key] = trim($val);
}
The simplest, and cleanest (in my opinion), is to use the built in array_map function:
array_map('trim', $_POST);
You can also apply a method of your own by passing an array as the first callback-parameter like so:
array_map(array('My_Class', 'staticMethod'), $_POST); // Invoke a static method
array_map(array($myObject, 'objectMethod'), $_POST);
// Invoke $myObject->objectMethod for each element of $_POST
Update based on a comment below
Sometimes the $_POST array may contain arrays. If you want to trim contents of those arrays as well, there are many custom implementations of array_map_recursive available in the PHP manual user notes. Go there and choose one for yourself. If you don't like to take a custom implementation, array_walk_recursive is also a good option for you.
You can do this with array_walk().
Using recursive function you can do that.
PHP
// Static $_POST Array.
$_POST['1']='one ';
$_POST['2']=' two';
$_POST['3'][]=' three ';
$_POST['4'][][]=' four';
$_POST['5'][0][1][3]='five ';
// Recursive function for trim data.
function trim_recursive($array){
$return = array();
foreach($array as $key=>$values){
if(is_array($values)===true){
$return[$key] = trim_recursive($values);
}
else{
$return[$key] = trim($values);
}
}
return $return;
}
// Usage.
$_POST = trim_recursive($_POST);
Output
// Output before trim.
array(5) {
[1]=>
string(4) "one "
[2]=>
string(4) " two"
[3]=>
array(1) {
[0]=>
string(9) " three "
}
[4]=>
array(1) {
[0]=>
array(1) {
[0]=>
string(5) " four"
}
}
[5]=>
array(1) {
[0]=>
array(1) {
[1]=>
array(1) {
[3]=>
string(5) "five "
}
}
}
}
// Output after trim.
array(5) {
[1]=>
string(3) "one"
[2]=>
string(3) "two"
[3]=>
array(1) {
[0]=>
string(5) "three"
}
[4]=>
array(1) {
[0]=>
array(1) {
[0]=>
string(4) "four"
}
}
[5]=>
array(1) {
[0]=>
array(1) {
[1]=>
array(1) {
[3]=>
string(4) "five"
}
}
}
}