I am creating a small web application and I am running on two arrays - one retrieved by simplexml_load_file and the other generated by query to database. I have a little problem with the latter - I need to create an associative array that I can reference through indexes. For that I do something like that.
$stmt->execute();
$db = $stmt->fetchAll(PDO::FETCH_ASSOC);
The array should therefore look like this:
Array (
['element'] => value,
)
It looks like this:
Array (
[0] => Array (
['element'] => value,
)
)
The only thing I noticed was that in the query the records are created so
Array (
[0] => Array (
['element'] => value,
[0] => value
)
)
My solution removes indexes inside the first array, in this example it will remove the line [0] => value, although the main index will remain. How can I change this to result in a full associative associative array? I mention that I want to display all the records from the query, the same fetch () works, although it displays one record (last) from the query.
Try to change
From
$db = $stmt->fetchAll(PDO::FETCH_ASSOC);
To
$db = $stmt->fetch(PDO::FETCH_ASSOC);
PDOStatement::fetch — Fetches the next row from a result set
While PDOStatement::fetchAll — Returns an array containing all of the result set rows
The 0 means row one. If you want to process only one row use the current function on the array which will give you expected results
Related
I'm new to using $pdo statements so might be something simple I haven't yet read on php.net. I'm receiving duplicate results when querying the database.
Result:
[0] => Array
(
[umeta_id] => 31
[0] => 31
[user_id] => 2
[1] => 2
[meta_key] => fbmeta
[2] => fbmeta
[meta_value] => someMetaValueStuff;
[3] => someMetaValueStuff;
)
The query is quite simple:
function getData(){
global $pdo;
$query = $pdo->prepare('SELECT * FROM usermeta WHERE meta_key = "fbmeta" LIMIT 0,30');
$query->execute();
return $query->fetchAll();
}
print_r( getData() );
The problem is that the named keys (umeta_id, user_id, meta_key, meta_value) DO exist, the numeric keys do not. How come the query returns these? And how do I prevent them from even being returned?
It's not duplicates, it's just the current FETCH_MODE you're using. To get as associative keys only you need to specify as such; by default it fetches as both.
Use like so:
$query->fetchAll(PDO::FETCH_NUM); // to fetch with numeric indexes
$query->fetchAll(PDO::FETCH_ASSOC); // to fetch with associative indexes
fetchAll docs
fetch docs
This is not duplicate data fetchAll returns data in numeric array as well as associative array.
See the Docs
Use this for retrieving only associative array
return $query->fetchAll(PDO::FETCH_ASSOC);
seems to do the trick for me. Put this on top
use Illuminate\Database\Events\StatementPrepared;
when ever fetching include pdo::fetch_assoc
return($pdo->fetchAll(\PDO::FETCH_ASSOC));
I am reading a GEDCOM-formatted family tree flat file, and producing an array from the data for staging into table. If I encounter the values CONC <some value>, then, instead of adding an element, I need to append <some value> to the value of the last element that was just inserted (regardless of dimension depth).
I tried with current(...) etc but does this work for a multidimensional associative array?
please consider following element in an array:
[#N163#] => Array ( [INDI] => Array ( [TEXT] => Some data of this person) )
if the next line reads "1 CONC including his profession"
instead of adding a line as such
[#N163#] => Array (
[INDI] => Array ( [TEXT] => Some data of this person)
[INDI] => Array ( [CONC] => including his profession) )
I would like the array to look as follows:
[#N163#] => Array (
[INDI] => Array ( [TEXT] => Some data of this person including his profession) )
What I have researched thus far:
end($theArray)
to set pointer to last inserted element followed by $theArray[key($theArray)] = .... to update this element.
But I did not get this method to work for multidimensional arrays and/or it became really messy.
And:
merging two arrays using e.g. += notation,
but this only seems to overwrite a new element, not affect the last one, if keys are same
And:
examples with foreach calls, which does not help in my case.
Hope somebody can shed some light... many thanks!
When you adding $array[#N163#][INDI][TEXT] = 'smtng'; you can save position
$pos = &$array[#N163#][INDI][TEXT];
And if you need concatenate, write
$pos .= "concate line";
I have an array that is assigned to $elements. When I use array_keys to get the keys, I get what you would expect.
print_r(array_keys($elements));
Results in:
Array
(
[0] => anchor-namecontentblock_areaBlock0contentblock11_1
[1] => anchor-namecontentblock_areaBlock0contentblock22_1
[2] => anchor-namecontentblock_areaBlock0contentblock33_1
...
But when I try to use array_keys with a search value, I get an empty array.
print_r(array_keys($elements, "anchor-namecontentblock_areaBlock0contentblock11_1"));
Should the result not be:
Array
(
[0] => 0
)
Am I missing something?
You're doing the wrong array_keys search. Your anchor-name... values are KEYS in the original array, not VALUES. As such, your array_keys search argument is useless - it'll be searching the values of the original array, e.g.
$foo = array(
'anchor-namecontentblock_areaBlock0contentblock11_1' => 'somevalue'
etc..
searched by array_keys---------^^^^^^^^^^
You'd need do something more like:
$results = array_search('anchor-name...', array_keys($elements)));
^^^^^^^^^^^^^
instead.
Specifying a search parameter to array_keys allows you to retrieve the key(s) corresponding to one or more values in your array. You're passing it one of your array keys, so the function is returning no results.
aside from doing the actual work of iterating through an associative array, pushing a value into a new array and setting that equal the array of remaining fields, is there an array function built into PHP that would do something like this?
if so, what is it?
i would be changing the following:
Array
(
[0] => Array
(
[0] => TEST //Name (Database column name
[1] => 12430 //ID (Database column name
[2] => Y //Save (Database column name
[3] => 100 //Wert (Database column name
)
into something like this:
Array
(
[12430] => Array
(
[Name] => TEST
[Save] => Y
[Wert] => 100
)
i work with while-loop:
....
while( $row = mysql_fetch_assoc($ergebnis) ) {
....
}
I think that you are going to have to iterate through the array. There may be a function here that could shorten the code by about a line, but I doubt it will make a noticeable difference to the readability and efficiency of your code.
So I would iterate through the array if I were your, quite short and simple.
$new_array = array();
while( $row = mysql_fetch_assoc($ergebnis) ) {
$new_array[$row[1]] = $row;
unset($new_array[$row[1]]);
}
Note that the mysql_ functions have been deprecated in PHP and you should be using mysqli_ or PDO instead, as it is more stable and secure.
Also, as #CBroe said, the mysql_fetch_assoc function will return the second part of your desired result already. The equivalent in PDO would be $query->fetch(PDO::FETCH_ASSOC);
Good luck!
Alter your query and add GROUP BY ID at the end.
I have an array that looks like this
Array
(
[0] => Array
(
[Title] => The Title
[Price] => 700
[Quantity] => 2
)
)
Say I wanted to change the Quantity to 5 how would I do that if the array were stored in the variable $ItemArray?
Try $itemArray[0]['Quantity'] = 5;.
Basically, you have an array, $itemArray, which contains an associative array. To access that inside array, you simply use standard PHP array syntax: $itemArray[0].
Then, you need the Quantity field of that inner array. Using the nested array syntax, you append ['Quantity'] to the end of our previous statement, resulting in: $itemArray[0]['Quantity'].
At this point, you have the field you want, and you can use the normal = to set the field value.
$itemArray[0]['Quantity'] = 5;
thats very simple, try
$itemArray[0]["Quantity"] = 5;
What we're doing here is accessing the first index within $itemArray which is 0; 0 contains an array, so we now specify which part of 0 we want to access: Like this basically:
$array[index][innerarrayindex]