I am trying to figure out how to get values out of a checkbox array. The checkbox array var_dump looks like the following:
array (size=50)
0 => string '104702|0' (length=8)
1 => string '52278|1' (length=7)
2 => string '69891|1' (length=7)
3 => string '153335|1' (length=8)
4 => string '131140|1' (length=8)
. . .
I am sending two different IDs in each array value, separated by a pipe and would like to assign each part to different variables, $variable1, $variable2, so I can use them in a database query. How can I do this?
Thanks for your help.
EDIT: Even though I've accepted an answer below, here is the complete answer I was looking for:
To get the values out of the above array so I can use them in my database query, I did the following to first break them apart:
foreach ($input as $key => $value) {
$this->combinedIds[] = explode('|', $value);
}
Then, to get the values into separate variables, I did the following:
foreach ($this->combinedIds as $key => $value) {
$firstId = $value[0];
$secondId = $value[1]
// do something with the values ...
}
Use foreach loop on the array and explode each value with pipe symbol. Something like this :
foreach ($arr as $val)
{
$newData = explode("|", $val);
}
A different variant (using an anonymous function) would be something like:
$values = array_map(function ($input) { $tmp = explode("|", $input); return ["id1" => current($tmp), "id2" => end($tmp)]; }, $array);.
This is written for PHP 5.4+. If you need a version compatible with PHP 5.3 and downwards, just substitute the brackets with its corresponding array(...) equivalent.
Related
I am inserting string with multiple delimiters and split it using explode function to mysql database table but i failed in building proper logic.
I tried with single delimiter i-e , and successfully insert that record.
Now i want to split string with | and ,.
I used for row separation and | for value seperation.
i-e
$var = "Facebook|http://facebook.com/123|12312|12 to 13,Twitter|http://twitter.com/231|12321|12 to 13";
$cat="2,3";
$i=0;
$arrayOfCategories = explode(",", $cat);
foreach ($arrayOfCategories as $categories) {
$datas[$i]['UserID'] = 2;
$datas[$i]['CatID'] = $categories;
$i++;
}
var_dump($datas);
Format showed using var_dump is the format which i want to insert using insert_batch of codeigniter.
This is the expected output
array (size=2)
0 => array (size=2)
'SocialName' => string 'Facebook'
'URL' => string 'facebook.com/123'
1 => array (size=2)
'SocialName' => string 'Twitter'
'URL' => string 'twitter.com/231'
$array = array();
$string = "Facebook|http://facebook.com/123|12312|12 to 13,Twitter|http://twitter.com/231|12321|12 to 13";
$rows = explode(',', $string);
foreach ($rows as $row) {
$values = explode('|', $row);
$array[] = array('SocialName' => $values[0], 'URL' => $values[1]);
}
var_dump($array);
Create an array $array to store the final result in.
Now, split the input string $string on , using explode, this gives you the "rows".
Go through all the rows (foreach), and split each row on the | (explode), this gives you the "values".
The first value $values[0] is the "SocialName", and the second value $values[1] is the "URL", so add those to a new array, and add that new array to the final result array $array.
I am trying to loop over certain array keys in drupal, but this is more of a generic php array question.
The array looks something like this...
$form['items'] = array(
#title => 'hello',
0 => array(
#subtitle => 'hello2';
),
1 => array(
#subtitle => 'hello2';
),
#prefix => '<div>hello</div>',
);
As you can see, the keys are a mix of numeric keys and #meta keys.
I am using this...
foreach($form['items'] as $x) {
unset($form['items'][$x]['column1']);
}
But i only want to target the numeric keys, I have tried is_numeric but it returned false.
Can someone tell me how to ignore the other keys? (Ignore #title and #prefix etc)
You want to check the keys, but you are using the value in your foreach. Do the following:
foreach($form['items'] as $key => $value) {
if (is_numeric($key))
unset($form['items'][$key]);
}
Hope I was helpful
Use is_int() rather than is_numberic()
foreach ($input_array as $key => $val) {
if (is_int($key)) {
// do stuff
}
}
Important to note that is_int only works on things that are type integer, meaning string representations are not allowed.
I have a string:
01;Tommy;32;Coder&&02;Annie;20;Seller
I want it like this:
array (size=2)
0 =>
array (size=4)
0 => string '01' (length=2)
1 => string 'Tommy' (length=5)
2 => int 42
3 => string 'Coder' (length=5)
1 =>
array (size=4)
0 => string '02' (length=2)
1 => string 'Annie' (length=5)
2 => int 20
3 => string 'Seller' (length=6)
Hope you can help me, thank you!
Not sure if the datatypes will be matching (as I believe it's all in a string) but here's the code
$myarray = array();
foreach(explode("&&",$mystring) as $key=>$val)
{
$myarray[] = explode(";",$val);
}
The explode command takes a string and turns it into an array based on a certain 'split key' which is && in your case
but since this is a dual array, I had to pass it through a foreach and another explode to solve.
It's very simple. First you need to explode the string by && and then traverse through array exploded by &&. And explode each element of an array by ;.
Like this,
<?php
$str="01;Tommy;32;Coder&&02;Annie;20;Seller";
$array=explode("&&",$str);
foreach($array as $key=>$val){
$array[$key]=explode(";",$val);
}
print_r($array);
Demo: https://eval.in/629507
you should just have to split on '&&', then split the results by ';' to create your new two dimensional array:
// $string = '01;Tommy;32;Coder&&02;Annie;20;Seller';
// declare output
$output = [];
// create array of item strings
$itemarray = explode('&&',$string);
// loop through item strings
foreach($itemarray as $itemstring) {
// create array of item values
$subarray = explode(';',$itemstring);
// cast age to int
$subarray[2] = (int) $subarray[2]; // only useful for validation
// push subarray onto output array
$output[] = $subarray;
}
// $output = [['01','Tommy',32,'Coder'],['02','Annie',20,'Seller']];
keep in mind that since php variables are not typed, casting of strings to ints or keeping ints as strings will only last depending on how the values are used, however variable type casting can help validate data and keep the wrong kind of values out of your objects.
good luck!
There is another appropach of solving this problem. Here I used array_map() with anonymous function:
$string = '01;Tommy;32;Coder&&02;Annie;20;Seller';
$result = array_map(function($value){return explode(';',$value);}, explode('&&', $string));
Our Story: (short version below if you're eager to troubleshoot)
This question is asked after extensively searching for a way to get a multidimensional array (with named keys) back into it's CSV file. You might say: "But this is covered on multiple pages on SO, search better!" but we did, and the results we found we have tried to bend to our will, but failed.
The reason for this in the first place was to remove columns from the CSV that were interfering with the rest of our Query's and Code.
So now we're back to ask on SO:
We've read the CSV into a multidimensional Array, using the headers' 1st line as key names.
We then used unset($array[$i]['insert_date']); to remove the columns from the array
We also str_replace'd those columns names from our $header variable.
So we're extensively reading out csv's, putting them in awesome Arrays that have a numerical first index, and second dimension keys named after the first line of our CSV file.
We also have the original Header from CSV file stored in a variable handsomely called $header with a string like: '"brand";"category";"category_path"
So.. $header is a string, $array is our multidimensional array.
All we want to do, and we're stuck editing loop after loop, is to create a brand new File, that has our $header as the first line, and our $array's values as strings..
file to write to: $putfile = fopen("feeds/broken/lu-zz.csv", "rw");
we're using: fputcsv($file, $array,';','"'); to write
and preferably: \n line endings
In short:
from this:
array (size=3886)
0 =>
array (size=19)
'brand' => string 'Tommy Hilfiger' (length=14)
'category' => string '' (length=0)
'category_path' => string 'Heren|Jeans|Blue jeans' (length=22)
1 =>
array (size=19)
'brand' => string 'Marc Aurel' (length=10)
'category' => string '' (length=0)
'category_path' => string 'Dames|Jurken|Zomerjurken' (length=24)
2 =>
array (size=19)
'brand' => string 'Rinascimento' (length=12)
'category' => string '' (length=0)
'category_path' => string 'Dames|Jurken|Print jurken' (length=25)
To This
"brand";"category";"category_path"
"Tommy Hilfiger";"";"Heren|Jeans|Blue jeans" (/n)
"Marc Aurel";"";"Dames|Jurken|Zomerjurken" (/n)
"Rinascimento";"";"Dames|Jurken|Print jurken" (/n)
Last piece of code we tried:
{
foreach($subarray as $value){
for ($i=0, $m=count($value); $i<$m; $i++){
//$test = implode('";"',$subarray) ;
//$tmp = array();
$result = call_user_func_array('array_merge', $subarray);
//$tmp[]= array_merge($subsub[$i]);
var_dump($result);
fputcsv($putfile, $subarray,';','"');
}
}
} fclose($putfile);
This just returns the same value over and over again into an array:
foreach ($array as $subarray) {
foreach($subarray as $value){
for ($i=0, $m=count($value); $i<$m; $i++){
//$test = implode('";"',$subarray) ;
//$tmp = array();
print_r($subarray);
fputcsv($putfile, $subarray,';','"');
}
}
} fclose($putfile);
Solution in our case: Thanks to "Don't Panic" & "CBroe".
$putfile = fopen("feeds/stukkefeeds/lu-zz.csv", "wb");
$header = str_replace('"','',$header1);
$titel = explode(';',$header);
var_dump($titel);
// then write in your data
fputcsv($putfile, $titel,';','"');
foreach ($array as $line) {
fputcsv($putfile, $line,';','"');
}
It looks like you may be making it more complicated than it needs to be. If you have an $array that is the one you've shown that looks like:
array (size=3886)
0 =>
array (size=19)
'brand' => string 'Tommy Hilfiger' (length=14)
'category' => string '' (length=0)
'category_path' => string 'Heren|Jeans|Blue jeans' (length=22)
...
And you have a working file handle that you've opened with
$putfile = fopen("feeds/broken/lu-zz.csv", "w");
You shouldn't need a nested loop at all. You can get the header line by using array_keys on the first item in the array (or any item, really), write it to the file with fputcsv, and then loop over the array and write each line of data, also with fputcsv.
$first_line = reset($array); // get the first line
fputcsv($putfile, array_keys($first_line)); // use its keys to write the headers
// then write in your data
foreach ($array as $line) {
fputcsv($putfile, $line,';','"');
}
Looks like you are thinking way too complicated here ...
$firstIteration = true;
foreach($yourArray as $elem) {
if($firstIteration ) { // if this is the first array element,
// write out its keys to create the CSV heading line
echo implode(';', array_keys($elem)) .'<br>';
$firstIteration = false;
}
echo implode(';', $elem) .'<br>'; // output the data for each array element
}
(Notice that I used echo and implode here for demonstration purposes; the result will not have the enclosing " - switching that out for writing CSV to the file again should be no issue.)
I'm new to array and I have a decrypt function and sql query. Process is I query in the database and return the $get in an array like so:
array (size=1)
0 =>
array (size=3)
'Username' => string 'joenefloresca' (length=13)
'MiddleName' => string 'Estero' (length=6)
'Email' => string 'joenefloresca#gmail.com' (length=23)
What I want is to use my decrpyt function (data is encrypted, above is just an example). When I decrypt
it I want it to overwrite $get array with the decrypted values. I can do it this way,
foreach( $get as $key => $result )
{
$get[$key]['Username'] = $decr->decrypt($result['Username']);
$get[$key]['MiddleName'] = $decr->decrypt($result['MiddleName']);
$get[$key]['Email'] = $decr->decrypt($result['Email']);
}
But I can do that if my Fields like Username,MiddleName,Email is fixed in the sql query, what if
it is dynamic? Fields in the query is defined by the user, ex. What if Username is the only field? or Username and Email only? How can I overwrite the array with the decrypted one with the selected Field only?
Thanks.
Just nest another loop inside if you do not want to explicitly set the index you want:
foreach($get as $key => $result) {
foreach($result as $k => $val) { // will loop for each piece/copy of `$result`
$get[$key][$k] = $decr->decrypt($val);
}
}