By default mysql_fetch_array returns numeric and associative array togeather. This function is useful for reading, while you can get values
either by statement :
echo arr[1]; //circle
or
echo arr["shape"]; //circle
I am new to PHP and I run into the troubles when I wanted to change the values of that fetched array:
arr[1] = square;
I supposed that arr["shape"] will be 'square' too, but I was wrong. arr["shape"] still remains 'circle'.
Obviously you have to change both values to 'circle'.
Moreover: I wrote a funcion which should return changed shape array, (which is 2D array). I got different outcomes, if I used the first or
the second line of code.
function ChangeShape($arr)
{
for ($i=0; $i<$count($arr); $i++)
{
1. $arr[$i]["shape"] = 'square'; // fail to return changed $arr - it is (probably) reference to number counterpart
2. $arr[$i][2] = 'square'; // this WILL return changed $arr
}
}
return $arr;
}
My questions:
1. is there any technique in PHP by which I can change both values at once?
2. in my app I use assoc nicknames to access array values. But when it is not possible to change numeric alias at the same time, what is
the easiest way to do it?
thank for reading this to the end... hope you answer.
Thanks a lot.
If you just want the data in a simple array once you grab it, you can always just simplify it by putting it in a few array:
$query = "SELECT * from myTable";
$result = mysql_query($query) or die(mysql_error());
$newArray = array();
$i=0;
while($row = mysql_fetch_array($result)){
array_push( $newArray, $row[$i]['name'] );
}
print_r($newArray);
$newArray[4] = "some other value than what came from the db";
print_r($newArray);
It doesn't seem super clear why your data is coming back as complicated as it seems to be, but this might help clear it up.
Do you really need to fetch numeric index? At least based on what you've posted it seems like you just want to call mysql_fetch_assoc to get an array with just the associative version.
The "aliases" in the array returned by mysql_fetch_array aren't really aliases... it just inserts it twice into the result array, once with the numeric index and once with the name of the column. The only way to change them both is to assign them both the desired value.
See this example and maybe it will make sense why its not working. Its not a reference or it would be working. If you had to have this functionality, you could build your array like this:
<?
$a='dog';
$b='cat';
$arr=array ('a' => &$a, 1 => &$a,'b' => &$b,'2' => &$b );
print_r($arr);
$a='horse';
print_r($arr);
$arr[1]='cow';
print_r($arr);
Results:
Array
(
[a] => dog
[1] => dog
[b] => cat
[2] => cat
)
Array
(
[a] => horse
[1] => horse
[b] => cat
[2] => cat
)
Array
(
[a] => cow
[1] => cow
[b] => cat
[2] => cat
)
Related
Very simplified example:
function returnArray() {
return array('First','Second','Third');
}
$arr = array('hello','world');
$arr[] = returnArray();
print_r($arr);
I was (wrongly) expecting to see $arr containing 5 elements, but it actually contains this (and I understand it makes sense):
Array
(
[0] => hello
[1] => world
[2] => Array
(
[0] => First
[1] => Second
[2] => Third
)
)
Easily enough, I "fixed" it using a temporary array, scanning through its elements, and adding the elements one by one to the $arr array.
But I guess/hope that there must be a way to tell PHP to add the elements automatically one by one, instead of creating a "child" array within the first one, right? Thanks!
You can use array_merge,
$arr = array_merge($arr, returnArray());
will result in
Array
(
[0] => hello
[1] => world
[2] => First
[3] => Second
[4] => Third
)
This will work smoothly here, since your arrays both have numeric keys. If the keys were strings, you’d had to be more careful (resp. decide if that would be the result you want, or not), because
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
You are appending the resulting array to previously created array. Instead of the use array merge.
function returnArray() {
return array('First','Second','Third');
}
$arr = array('hello','world');
$arr = array_merge($arr, returnArray());
print_r($arr);
I'm getting started with PHP and I have some troubles finding a way to output values from multiples arrays sent from an external site.
I did a foreach and the code that is printed looks like this :
Array
(
[id] => 1
[title] => Title 1
)
Array
(
[id] => 2
[title] => Title 2
)
Array
(
[id] => 3
[title] => Title 3
)
Any idea how I could get every id (1,2,3) in an echo?
Let me know if you need more informations!
Thanks a lot!
If you just want to echo all the id's in all the arrays, a simple solution would be:
foreach ([$array1, $array2, $array3] as $arr) {
echo $arr['id'];
}
A better solution would probably to create one main array first:
$mainArray = [];
and every time you get a new array, you just push them to the main array:
$mainArray[] = $array1;
$mainArray[] = $array2;
// ... and so on
Then you'll have a multi dimensional array and can loop them with:
foreach ($mainArray as $arr) {
echo $arr['id'];
}
Which solution that works best depends on how you get the arrays and how many they are.
Note: Using array_merge() as others have suggested will not work in this case, since all the arrays have the same keys. From the documentation on array_merge(): "If the input arrays have the same string keys, then the later value for that key will overwrite the previous one."
As you can do:
$array = array_merge_recursive($arr1, $arr2, $arr3);
var_dump($newArray['id']);
echo implode(",", $newArray['id']);
A demo code is here
I am trying to separate an array into two separate arrays. For example, if I have an array like this
Array([0]=>Hello[1]=>I'm[2]=>Cam)
I want to split it into two arrays and add another string
Array1([0]=>Hello[1]=>There,)
Array2([0]=>I'm[1]=>Cam)
Then finally add the two together
Array([0]=>Hello[1]=>There,[2]=>I'm[3]=>Cam)
What would be the simplest way to do this?
I know I can use array merge to put the two together but I don't know how to separate them at a certain point.
I'm also doing this on a large file that will be constantly getting bigger, so I cant use array_chunk()
Looking at your end result goal, I think a shorter method to get your desired response is to use array_splice which lets you insert into a middle of an array....
$arrayVarOriginal = array('Hello', 'Im', 'Cam');
$arrayVarExtra = array('There');
array_splice($arrayVarOriginal, 1, 0, $arrayVarExtra);
This should send you back Array([0]=>Hello[1]=>There,[2]=>Im[3]=>Cam) like you wanted!
The above avoids having to split up the array.
HOWEVER
If you did want to do it the hard way, here is how you would...
$arrayVarOriginal = array('Hello', 'Im', 'Cam');
$array1stPart = array(arrayVarOriginal[0], 'There');
$array2ndPart = array_shift($array1stPart);
$finalArray = array_merge($array1stPart, $array2ndPart);
How? array_shift removes the first item from any array, so that how we get $array2ndPart.... and $array1stPart is even easier as we can just manually build up a brand new array and take the first item from $arrayVarOriginal which is at position 0 and add 'There' in as our own new position 1.
Hope that helps :)
array_shift, array_splice, and array_merge are what you need to look into.
Based from your question, here step-by-step to get what you want for your final output.
1) Split Array
$arr = array('Hello', 'I\'m', 'Cam');
$slice = count($arr) - 1;
$arr1 = array_slice($arr, 0, -$slice);
$arr2 = array_slice($arr,1);
so, you get two new array here $arr1 and $arr2
2) Add new string
$arr1[] = "There";
3) Finally, combine the array
$arr = array_merge($arr1, $arr2)
Here sample output when you print_r the $arr
Array
(
[0] => Hello
[1] => There
[2] => I'm
[3] => Cam
)
array_slice second parameter is position where you want split. So you can do this dynamically by count the array length.
$string = array("Hello","I'm","Cam");
$firstArray = array_slice($string ,0,1);
array_push($firstArray,"There,");
$secondArray = array_slice($string ,1,2);
echo "<pre>";
print_r($firstArray);
echo "==========="."<pre>";
print_r($secondArray);
echo "<pre>";
print_r(array_merge($firstArray,$secondArray));
//out put
Array
(
[0] => Hello
[1] => There,
)
===========
Array
(
[0] => I'm
[1] => Cam
)
Array
(
[0] => Hello
[1] => There,
[2] => I'm
[3] => Cam
)
Hope it will be worked for your requirement. If not or you need more specify regarding this you can clarify your need.
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 looks like
Array
(
[0] => 1213059
[1] => 1213063
[2] =>
[3] =>
[4] => 1213072
)
I would like to make it as following:
Array
(
[0] => 1213059
[1] => 1213063
[2] => 1213072
)
Is there anyone can help me?
Many thanks
Use array_filter
Check demo here:
array_values(array_filter($your_array)); to keep your keys numerically .
array_filter will remove all elements that evaluate to false:
$array = array_filter($array);
I don't think answers above give correct fields order, as it was asked. If you only want to remove some fields from array and leave keys order untouched you could do it with
array_filter($arr) or with unset($arr[$i])
But if you want to get new order of keys, so there is no "holes", in above example to set key 4 to key 2 as keys 2 and 3 are unset, you have to use
ksort($arr)
Here is a complete example:
$arr=array(1,1,3,2,0);
print_r($arr);
echo '<br>';
unset($arr[2]);
ksort($arr);
print_r($arr);
$arr=array_values($arr);#EDITED
ksort($arr) knows not to sort array as it should, so just in case add $arr=array_values($arr); on the end #EDITED
PHP reference of ksort() is on link.
You may use this workaround.
Define this function somewhere:
function removeArrElement($inArr, $elementNr) {
for ($i = $elementNr; $i < count($inArr) - 1; $i++) {
$inArr[$i] = $inArr[$i + 1];
}
unset($inArr[count($inArr) - 1]);
return $inArr;
}
And then, when you want to remove the specific element from $yourArray, do this:
$yourArray = removeArrElement($yourArray, $nthElement);
I feel it's not the most efficient way to do this, but it works fine.