I'm attempting to add a couple of columns to a multidimensional PHP array inside a loop.
Inside the loop I currently have this:
$html[]['strongsNum'] = $strongsCode;
$html[]['wordNum'] = $wordNumber;
However, because I'm not setting the index manually, it creates two separate entries for the two. How can I make it add the two columns to the one entry / row of the array?
try:
$html[] = array(
'strongsNum' => $strongsCode,
'wordNum' => $wordNumber,
);
$html[] = array(
'strongsNum' => $strongsCode,
'wordNum' => $wordNumber
);
If you don't want to use the array(key => value) syntax:
After adding the initial 'strongsNum', you can re-access the last member of your array by using count($myArray)-1 as the index.
$html[]['strongsNum'] = $strongsCode;
$html[count($html) - 1]['wordNum'] = $wordNumber;
Related
I need some help. I need to remove duplicate data as per key value using PHP. I am explaining my code below.
$orginalArr = array(
array("id"=>1,"name"=>"Raj"),
array("id"=>1,"name"=>"Raj"),
array("id"=>2,"name"=>"Ram"),
array("id"=>2,"name"=>"Ram"),
array("id"=>3,"name"=>"Rahul")
);
echo json_encode($orginalArr);
Here I need to remove the data as per id, meaning if id value is same then one set of data will be removed. Please help me.
Just iterate through values and push it to the new array.
Example:
<?php
$orginalArr=array(array("id"=>1,"name"=>"Raj"),array("id"=>1,"name"=>"Raj"),array("id"=>2,"name"=>"Ram"),array("id"=>2,"name"=>"Ram"),array("id"=>3,"name"=>"Rahul"));
$newArray = array();
foreach ( $orginalArr as $arr )
$newArray[$arr['id']] = array(
'id' => $arr['id'],
'name' => $arr['name']);
echo json_encode(array_values($newArray));
?>
I have fields in mySQL which is currently being stored like this under the field "tags"
Shopping|Health & Beauty
Coffee|Shopping
What I'm trying to do is to loop through this to create a single dimension array and to grab only the unique values.
I have my query selecting DISTINCT tags from TABLE and run the loop like this:
while ($row_tags = mysql_fetch_assoc($r_tags)) {
$tags = $row_tags['tags'];
$imploded_tags[] = explode("|",$tags);
}
echo "<pre>";
print_r($imploded_tags);
The result from the print_r is showing it as a multidimensional array. I've tried to reexplode it and implode it in different ways, but I haven't been able to get any success. Is there a way that I can create this into a single dimension array? Not all tags will have an equal amount of tags separated by |, so I can't seem to get it to go with a function that I tried from another StackOverflow post. Any help would be greatly appreciated!
OUTPUT:
Array
(
[0] => Array
(
[0] => Shopping
[1] => Health & Beauty
)
[1] => Array
(
[0] => Coffee
[1] => Shopping
)
try this
while ($row_tags = mysql_fetch_assoc($r_tags)) {
$tags = $row_tags['tags'];
$tags = explode("|",$tags);
foreach($tags as $v){
$imploded_tags[] = $v;
}
}
I would do something like:
$imploded_tags = array_merge(explode("|",$tags), $imploded_tags);
}
$imploded_tags = array_unique($imploded_tags);
echo "<pre>";
print_r($imploded_tags);
See the manual on array_merge and array_unique.
However, I do think you are not using the right way to store your tags; they should be stored in a separate table as separate values.
What's going on is when you're fetching your rows from MySQL, you're essentially getting a bunch of data in an array in the first place, which is why you have to loop through them.
With your your implode function, you're taking a bunch of strings, then getting another array set and then appending that to an external array.
If you really wanted to get a single dimensional array without having this multidimensional thing going on, all you really need to do is utilize another loop within that loop.
$all_tags = array();
while ($row_tags = mysql_fetch_assoc($r_tags)) {
$tags = $row_tags['tags'];
$imploded_tags[] = explode("|",$tags);
for($i = 0; $i < count($imploded_tags); $i++) {
$all_tags[] = $imploded_tags[$i]
}
}
print_r($all_tags);
Here is my code:
<?php
//header code to define as json and if $_GET statement...
$JSONArrayA[$variableA] = array('id' => $idA, 'test' => $testVariableA);
$JSONArrayB[$variableB] = array('id' => $idB, 'test' => $testVariableB);
//current code resulting in ["ArrayArray"]
$FinalJSONArray[] = $JSONArrayA . $JSONArrayB;
echo json_encode($FinalJSONArray);
?>
My question: How do I make the array contain two or more arrays? Any help appreciated.
array_merge
$FinalJSONArray = array_merge($JSONArrayA, $JSONArrayB);
Merges the elements of one or more arrays together so that the values
of one are appended to the end of the previous one. It returns the
resulting array.
If you want to instead return an array containing the other two arrays themselves,
use
$FinalJSONArray = array($JSONArrayA, $JSONArrayB);
Try
$FinalJSONArray[] = $JSONArrayA;
$FinalJSONArray[] = $JSONArrayB;
This will reult in 2 sub arrays. If you want them merged use:
$FinalJSONArray[] = $JSONArrayA+$JSONArrayB;
"+" with two arrays unions them (see: http://php.net/manual/en/language.operators.array.php)
Depending on what you want your JSON to look like
$FinalJSONArray = array($JSONArrayA,$JSONArrayB);
I have a multi-dimensional array of databases, which was generated from my server:
// place db tables into array
$da_db = array(
'test' => array(
// test.users
'users' => array('fname','lname','info'),
// test.webref_rss_details
'webref_rss_details' => array('id','title','link','description','language','image_title','image_link','item_desc','image_width','image_height','image_url','man_Edit','webmaster','copyright','pubDate','lastBuild','category','generator','docs','cloud','ttl','rating','textInput','skipHours','skipDays'),
// test.webref_rss_items
'webref_rss_items' => array('id','title','description','link','guid','pubDate','author','category','comments','enclosure','source','chan_id')
),
'db_danaldo' => array(
//code here
),
'frontacc' => array(
//code here
)
[array][db][table][field]
As you can see, the database currently populated refers to an RSS project I am working on - one table for Channels, another for Items in that channel, at the moment that is another issue ('Users' table for now is not important)..
what I want to do is to return the array/sub-array names and convert each into variables for use as part of a string in an SQL Query, also need an alias for the tables I need to connect with:
(e.g. SELECT * FROM 'webref_rss_items' WHERE 'chan_id' = 'test.webref_rss_details.id')
where 'webref_rss_items' is a variable, 'chan_id' is a variable and 'test.webref_rss_details.id' are 3 variables in a concatenated string, although I've heard the concatenation in an SQL Query is not good practice, security-wise.. the strange thing is of all of those values, all I can retreive is the deepest level, 'id':
echo "{$da_db['test']['webref_rss_details'][0]}"
but get 'Array' returned or the last value of an array when I try to access the names!!
The reason for this is that the PHP file with the query will be within the 'public' part of the server and would like to have use variables with have no connotation to the original name(s), also it seems more convenient as the variables can be interchangable and I won't be using the same path all the time.
EDIT: My idea is to get key names from ['db'] to ['field']. The closest I have reached is to iterate keys and array_fill in a foreach loop, use range() inside another foreach, array_combine both then var_dump combined array like so:
foreach($da_db['test'] as $key1 => $val) { //put key-names into array1 to use as values
$a = array();
$a = array_fill(0, 1, $key1);
print($key1.'<br />');
}
foreach (range(0, 2) as $number) { //array for numbers to use as keys
$b = array();
$b = array_fill(0, 1, $number);
echo $number.'<br />';
}
$c = array_combine($b, $a); //combine both for new array
print_r($c.'<br />');
I could the use array_slice to get the name I want! (long winded?)
The problem is that the result of this only shows the last key => value; depending on command(print_r, print, echo), it shows:
[2] => webref_rss_items
OR
Array.
I hope that is enough info for now.
I've seen similar questions on here, but normally apply to one value, or one level of an array, but if you have seen this question before please advise and point me in right direction.
Your two top level arrays (db name and table name) are "named-key" arrays. The field level array (value of table name array) is an "integer key" array. PHP automatically adds numerical indexes for arrays that are defined with values only. For "named-key" arrays, you can only access their values by using the key name you defined.
For example:
$array1 = array('zero', 'one', 'two');
echo $array1[2]; // two
$array2 = array('zero' => 'this is zero', 'one' => 'this is one');
echo $array2['zero']; // this is zero
echo $array2[0]; // undefined
PHP provides a function called array_keys() that will return you an integer index array with all the key names. So you access your table array using an integer value, you can do this.
$da_db_test_keys = array_keys($da_db['test']);
echo $da_db_test_keys[1];
Maybe this will help you a little bit. I wasn't 100% on how you planned on accessing the values in your arrays, so if you have any more questions please try to clarify that part.
I am attempting to generate a multi-dimensional array with each sub array representing a row I want to insert into my DB. The reason for this is so I can use CodeIgniters batch_insert function to add each row to the DB.
I am attempting to create each sub array within a loop and insert it into a multidimensional array. Google suggested using array_merge, but after using 'print_r' on the multidimensional array with the code below, only the last sub-array is being displayed.
Here is my code:
$allplayerdata = array(); //M-D container array
for ($i = 1; $i <= 11; $i++)
{
$playerdata = array(
'player_id' => $this->input->post('player' . $i),
'goals' => $this->input->post('playergoals' . $i),
'player_num' => $i,
'fixture_id' => $this->input->post('fixture_id')
);
//Merge each player row into same array to allow for batch insert
$allplayerdata = array_merge($allplayerdata, $playerdata);
}
print_r($allplayerdata);
Can anyone spot where I'm going wrong? Help is appreciated!
This is because array_merge is not the right operation for this situation. Since all the $playerdata arrays have the same keys, the values are overridden.
You want to use array_push to append to an array. This way you will get an array of $playerdata arrays.
array_push($allplayerdata, $playerdata);
Which is equivalent to adding an element with the square bracket syntax
$allplayerdata[] = $playerdata;
array_merge - Merge one or more arrays
array_push - Push one or more elements onto the end of array
Creating/modifying with square bracket syntax
This will add the second array to the first array: A merge is something different.
$allplayerdata[] = $playerdata;