I have an array I need formatted into a single array. The current function I have works well aside for I can't figure out how to set a custom key for the ID. The array is used to populate a select box, so I need that ID. I spent hours messing with it and I am just lost when it comes to formatting arrays.
I need the output to use a custom key (eg. $row->id ) which would output something like:
[40 =>'Florida', 50 =>'CA', 33 => 'NY']
Right now it outputting like..
[0 =>'Florida', 1 =>'CA', 2 => 'NY']
This is my current function:
protected function createRegionList($parent_id = '0', $spacing = '')
{
$arr = [];
foreach ($this->getByParentId($parent_id) as $row) {
$arr[] = $spacing . ' ' . $row->title;
$arr = array_merge($arr, $this->createRegionList($row->id, ' ' . $spacing . '—'));
}
return $arr;
}
Any help or suggestion would be much appreciated. I have found a bunch of examples, but they are more multidimensional arrays and I need the output as a single array.
You can set array item key by specifying the key in brackets. See PHP docs.
Try this
$arr[$row->id] = $spacing . ' ' . $row->title;
array_merge is not preserving keys. Use array_replace.
Or just union these together
$arr = [];
foreach ($this->getByParentId($parent_id) as $row) {
$arr[] = $spacing . ' ' . $row->title;
$childs = $this->createRegionList($row->id, ' ' . $spacing . '—');
$arr = $childs + $arr;
}
return $arr;
Related
I have an array with just a single element. The key and value looks like this:
Array ( [test] => 12342 )
Result i want is this inside an variable:
test = '12342'
I tried following:
$test = "'" . implode(" ", $metric) . "'";
print_r($test);
But this gives only gives me: '12342', i wanted the '=' after key and '' around the value (this is used for SQL later on). So the result should be test = '12342'. Does not look like implode would work here. I tried looking at http_query_builder but failed.
If this array is only ever going to contain one single item, then you don’t need to loop through the data, but you can use key and current instead:
$data = ['test' => 12342];
echo key($data) . " = '" . current($data) . "'";
key gets you the key of the “current” item, and current gets its value.
By just replying your question as it is using that unique example you would do it this way assuming there is only 1 value inside your array :
$yourArray = array('test' => '12342');
foreach($yourArray as $key => $value) {
$test = $key . " = '" . $value . "'";
}
print_r($test);
If there are multiple you would do this, as each key is unique :
$yourArray = array('test' => '12342', 'testing' => '24321');
$test = array();
foreach($yourArray as $key => $value) {
$test[$key] = $key . " = '" . $value . "'";
}
var_dump($test);
Is it possible to get / select first two character from an array value?
for example:
Array
Array
(
[0] => 1_name
[1] => 0_sex
[2] => 2_age
}
and I need to get the first two character from each value in array's elements. So I can get this as a result if I echo them.
Result
First Element is 1_
Second Element is 0_
Third Element is 2_
Anyone know how to solve this? thanks
You could use array_map to get new array with only the first two characters of each item:
$input = ['1_name', '0_sex', '2_age'];
var_dump(array_map(function($v) { return substr($v, 0, 2); }, $input));
Use a foreach loop this way:
<?php
$a = ["1_name",
"0_sex",
"2_age"];
foreach ($a as $aa) {
echo substr($aa, 0, 2) . "\n";
}
Output:
1_
0_
2_
You can use the array_map() function as well to return an array.
array_map(function ($a) {
return substr($a, 0, 2);
}, $input);
Using indexes will work for you as well.
Source-Code
index.php
<?php
$array = [
'1_name',
'0_sex',
'2_age'
];
echo 'First element is ' . $array[0][0] . $array[0][1] . '<br>';
echo 'Second element is ' . $array[1][0] . $array[1][1] . '<br>';
echo 'Third element is ' . $array[2][0] . $array[2][1] . '<br>';
Result
First element is 1_
Second element is 0_
Third element is 2_
I have a card deck array:
$cards = array("2_of hearts" => 2, "3_of_hearts" => 3, "king_of_hearts" => 10);
And I want to echo the name of the card somewhere (example: 2_of_hearts) but also calculate something with the number attached to it, but I really can't seem to make it work. Also, I was unable to find a working answer for me.
Does anyone know how to do this?
If you use a foreach loop that provides you with the key and the value like this, you get both the 2_of hearts and the 2 as variables.
$cards = array("2_of hearts" => 2, "3_of_hearts" => 3, "king_of_hearts" => 10);
foreach ( $cards as $name => $value) {
echo $name . ' has a value of ' . $value.PHP_EOL;
$calc = $value + 5;
echo 'ADDED 5 - gives ' . $calc . PHP_EOL;
}
Result
2_of hearts has a value of 2
ADDED 5 - gives 7
3_of_hearts has a value of 3
ADDED 5 - gives 8
king_of_hearts has a value of 10
ADDED 5 - gives 15
Then you just do your calculation with the $value variable
using this syntax of foreach lets you get access to the keys of the array
$cards = array("2_of hearts" => 2, "3_of_hearts" => 3, "king_of_hearts" => 10);
foreach($cards as $key=> $value){
$key = explode("_",$key);
$cardname = $key[count($key)-1];
//echo $key[0] . " of " $cardname . "<br>";
echo $value . " of " $cardname . "<br>"; // edit after comments
}
NOTE: this is off-course if you sure your keys are always has the pattern #_of_cardname
This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
Ok, I know that to get a comma-seperated string from a string array in PHP you could do
$stringA = array("cat","dog","mouse");
$commaSeperatedS = join(',', $stringA);
But what if I have an array of arrays(not a simple string array)?
$myAssociativeA =
array(
[0] => array("type"=>"cat", "sex"=>"male")
, [1] => array("type"=>"dog", "sex"=>"male")
);
and my goal is to get a comma-seperated string from a specific property in each array, such as "type"? Ive tried
$myGoal = join(',', $myAssociativeA{'type'});
My target value for $myGoal in this case would be "cat,dog".
Is there a simple way without having to manually loop through each array, extract the property, then do a join at the end?
This should work for you:
(Here I just get the column which you want with array_column() and simply implode it with implode())
echo implode(",", array_column($myAssociativeA, "type"));
Another option is to use array_walk() to return the key you want:
array_walk($myAssociativeA, function(&$value, $key, $return) {
$value = $value[$return];
}, 'type');
echo implode(', ', $myAssociativeA); // cat, dog
Useful for older PHP versions - #Rizier123's answer using array_column() is great for PHP 5.5.0+
You can use this if you have PHP < 5.5.0 and >= 5.3.0 (thanks to #Rizier123) and you can't use array_column()
<?php
$myAssociativeA = array(array("type"=>"cat", "sex"=>"male"), array("type"=>"dog", "sex"=>"male"));
$myGoal = implode(',', array_map(function($n) {return $n['type'];}, $myAssociativeA));
echo $myGoal;
?>
EDIT: with the recommendation in the comment of #scrowler the code now is:
<?php
$myAssociativeA = array(array("type"=>"cat", "sex"=>"male"), array("type"=>"dog", "sex"=>"male"));
$column = 'type';
$myGoal = implode(',', array_map(function($n) use ($column) {return $n[$column];}, $myAssociativeA));
echo $myGoal;
?>
Output:
cat,dog
Read more about array_map in:
http://php.net/manual/en/function.array-map.php
You just have to loop over the array and generate the string yourself.
<?php
$prepend = '';
$out = '';
$myAssociativeA = array(
array('type' => 'cat'),
array('type' => 'dog')
);
foreach($myAssociativeA as $item) {
$out .= $prepend.$item['type'];
$prepend = ', ';
}
echo $out;
?>
You could easily turn this into a function.
<?php
function implode_child($array,$key) {
$prepend = '';
$out = '';
foreach($array as $item) {
$out .= $prepend.$item[$key];
$prepend = ', ';
}
return $out;
}
?>
Ok, under assumption that your assoc array fields are ordered always the same way you could use snippet like this. Yet you still need to iterate over the array.
$csvString = "";
foreach ( $myAssociativeA as $row ) {
$csvRow = implode(",", $row);
$csvString .= $csvRow . PHP_EOL;
}
Now if you don't want to store whole CSV in a variable (which you should not do) take a look at http://www.w3schools.com/php/func_filesystem_fputcsv.asp and see an example how to put it directly into the file.
Some assistance would be greatly appreciated:
The 'foreach' section works perfectly and echo's the result set perfectly; as soon as I try the implode it fails? Thank you!
$ctr = 0;
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$RespondentsResultSetArray[$ctr] = array(
"Firstname" => $row['cnt_firstname'],
"Lastname" => $row['cnt_lastname']
);
$ctr = $ctr + 1;
}
foreach ($RespondentsResultSetArray as $key) {
echo $key["Firstname"] . ' ' . $key["Lastname"] . ', ';
}
sqlsrv_free_stmt($stmt);
echo implode(', ',array_values($RespondentsResultSetArray));
try this
implode(',',$RespondentsResultSetArray);
You are passing an array of arrays to implode function. Here is a little deviation of your code, that should get you to the same result:
$full_array = array();
foreach ($RespondentsResultSetArray as $key) {
echo $key["Firstname"] . ' ' . $key["Lastname"] . ', ';
array_push($full_array,$key["Firstname"]);
array_push($full_array,$key["Lastname"]);
}
echo implode(', ',$full_array);
Also, for the future, try to chose smaller names for your variables, and use lowercase for your variable names and array index.
The php implode function accepts an array of strings.
You are not passing it an array of strings.
To user1844933 that just answered, your suggestion would pass implode an array of arrays. That won't work for the same reason.
$RespondentsResultSetArray=array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
array_push($RespondentsResultSetArray,$row['cnt_firstname'].' '.$row['cnt_lastname']);
}
$saved_to_variable=implode(', '$RespondentsResultSetArray);
Will create an array of strings which you can then implode
Since you recently commented that you want to save it to a variable rather than echo it, I just changed the last line of the example code. I believe that will give you the properly spaced, and delimited string that you desire.
since$RespondentsResultSetArray is multidimensional array use foreach loop before echo
$string = "";
foreach($RespondentsResultSetArray as $values)
{
echo implode(array_values($values),",");
$string= $string.",".implode(array_values($values),",");
}
$string=ltrim($string,",");
echo $string;
Demo