Can anyone help output a multidimensional array, please.
Not to sure where I have gone wrong.
The sort ordering looks correct, but its not displaying the results.
<?php
$atest = Array ( "0" => Array ( "id" => "913", "testname" => "qwerty1", "i" => "1" ),
"1" => Array ( "id" => "913", "testname" => "test22", "i" => "2" ),
"2" => Array ( "id" => "913", "testname" => "American1", "i" => "3" ),
"3" => Array ( "id" => "913", "testname" => "Eagle4", "i" => "4" ) );
$range = range('A','Z');
$output = array();
$output['#'] = array();
foreach($range as $letter){
$output[$letter] = array();
}
foreach($atest as $test){
if ($test["testname"] !='') {
$uc = ucfirst($test["testname"]);
if(array_search($uc[0], $range) === FALSE){
$output['#'][] = $uc;
} else {
$output[$uc[0]][] = $uc;
}
}
}
foreach($output AS $letter => $result){
echo $letter . "<br/>--------<br/>\n";
sort($result);
foreach($result AS $indresult){
echo '' . $indresult['testname'] . '<br/>';
}
echo "<br/>\n";
}
?>
You're not putting the whole sub-array into $output, you're only putting $uc. Change the middle foreach loop to:
foreach($atest as $test){
if ($test["testname"] !='') {
$uc = ucfirst($test["testname"]);
if(array_search($uc[0], $range) === FALSE){
$output['#'][] = $test;
} else {
$output[$uc[0]][] = $test;
}
}
}
Try to use print_r function, for example for array dump:
print_r($atest);
Try this
$output[$uc[0]][] = $test;
instead of
$output[$uc[0]][] = $uc; // only the name is stored.
See demo here
Related
Lets say i have this array:
$first = ['hi', 'by', 'nice']
I am going to assign another array to this array items.In fact doing a foreach loop and due to situation assign a new array to desired array item.
Now i want turn it to this:
$second = ['hi', 'by' => ['really' => 'yes'], 'nice']
How can i do it programmatically?
Try this
$first = ['hi', 'by', 'nice'];
foreach( $first as $key => $value )
{
$second[] = $value;
if( $value == 'by' )
{
$second[ $value ][] = array( 'really' => 'yes' );
}
}
var_dump( $second );
Output:
array(4) {
[0]=>
string(2) "hi"
[1]=>
string(2) "by"
["by"]=>
array(1) {
[0]=>
array(1) {
["really"]=>
string(3) "yes"
}
}
[2]=>
string(4) "nice"
}
This is very important, if index by is known than you can use this index for checking and store values into a new array otherwise this will failed.
Here is basic example:
<?php
$first = ['hi', 'by', 'nice'];
$newArr = array();
foreach ($first as $key => $value) {
if($value == 'by'){
$newArr[$value] = array('really'=>'yes');
}
else{
$newArr[] = $value;
}
}
echo "<pre>";
print_r($newArr);
?>
Result:
Array
(
[0] => hi
[by] => Array
(
[really] => yes
)
[1] => nice
)
If I understand your requirement, actually there are many way exists to do this. This is mine,
<?php
$first = ['hi', 'by', 'nice'];
foreach($first as $k=>$v){
if($v !='by'){
$second[] = $v;
}else{
$second[$v] = ['really'=>'yes'];
}
}
print_r($second);
?>
Try this :
$second = $first;
$tofind = 'by';
$key = array_search($tofind, $second);
unset($second[$key]);
$second[$tofind] = array( 'really' => 'yes' );
I have an array called $context with this structure:
array(2) {
[0]=>
array(2) {
["name"]=>
string(6) "Foo"
["username"]=>
string(6) "Test"
}
[1]=>
array(2) {
["name"]=>
string(4) "John"
["username"]=>
string(3) "Doe"
}
}
I want convert it into this string:
string 1:
0: array(
'name' => 'Foo',
'username' => 'Test',
)
string 2:
1: array(
'name' => 'John',
'username' => 'Doe',
)
How you can see I want save the current index in the iteration and display the array content formatted as 'name' and 'username' in a single line. I already tried with this code:
$export = '';
foreach($context as $key => $value)
{
$export .= "{$key}: ";
print_r($value);
$export .= preg_replace(array(
'/=>\s+([a-zA-Z])/im',
'/array\(\s+\)/im',
'/^ |\G /m'
), array(
'=> $1',
'array()',
' '
), str_replace('array (', 'array(', var_export($value, true)));
print_r($export);
$export .= PHP_EOL;
}
return str_replace(array('\\\\', '\\\''), array('\\', '\''), rtrim($export));
but I'm looking for a more optimized solution, any suggest?
This is my code:
$context = [['name'=>'Foo','username'=>'Test'],['name'=>'John','username'=>'Doe']];
$schema = " '%s' => '%s'";
$lineBreak = PHP_EOL;
foreach( $context as $idx => $array )
{
$lines = array();
foreach( $array as $key => $val )
{
$lines[] = sprintf( $schema, $key, $val );
}
$output = "{$idx}: array({$lineBreak}".implode( ",{$lineBreak}", $lines )."{$lineBreak})";
echo $output.$lineBreak;
}
3v4l.org demo
It will works independently from the number of elements in sub-arrays
I have used classic built-in function sprintf to format each array row: see more.
You can change $lineBreak with you preferred endLine character;
In the above example, each string is printed, but (you have a return in your function, so i think inside a function), you can modify in this way:
$output = array();
foreach( $context as $idx => $array )
{
(...)
$output[] = "{$idx}: array({$lineBreak}".implode( ",{$lineBreak}", $lines )."{$lineBreak})";
}
to have an array filled with formatted string.
You can easly transform it in a function:
function contextToString( $context, $schema=Null, $lineBreak=PHP_EOL )
{
if( !$schema ) $schema = " '%s' => '%s'";
$output = array();
foreach( $context as $idx => $array )
{
$lines = array();
foreach( $array as $key => $val )
{
$lines[] = sprintf( $schema, $key, $val );
}
$output[] = "{$idx}: array({$lineBreak}".implode( ",{$lineBreak}", $lines )."{$lineBreak})";
}
return implode( $lineBreak, $output );
}
to change each time the schema and the line break.
PS: I see that in you code there is a comma also at the end of the last element of eache array; thinking it was a typo, I have omitted it
Edit: I have forgot the comma, added-it.
Edit 2: Added complete function example.
Edit 3: Added link to sprintf PHP page
Try this with personnal toString
$a = array(array("name"=>"Foo", "username"=>"Test"), array("name"=>"John", "username"=>"Doe"));
function toString($array){
$s = ""; $i=0;
foreach ($array as $key => $value) {
$s.= $key."=>".$value;
if($i < count($array)-1)
$s.=",";
$i++;
}
return $s;
}
$result = array();
$index = 0;
foreach ($a as $value) {
array_push($result, $index. " : array(" . toString($value).")");
$index ++;
}
var_dump($result);
And the result :
array (size=2)
0 => string '0 : array(name=>Foo,username=>Test)' (length=35)
1 => string '1 : array(name=>John,username=>Doe)' (length=35)
The result is in an array but you can change and make what you want
But you can also use json_encode :
$result = array();
$index = 0;
foreach ($a as $value) {
array_push($result, $index. " : array(" . json_encode($value).")");
$index ++;
}
var_dump($result);
With this result :
array (size=2)
0 => string '0 : array({"name":"Foo","username":"Test"})' (length=43)
1 => string '1 : array({"name":"John","username":"Doe"})' (length=43)
Simplified solution with strrpos,substr_replace and var_export:
$arr = [
array(
'name' => 'John',
'username' => 'Doe'
),
array(
'name' => 'Mike',
'username' => 'Tyson'
)
];
/*****************/
$strings = [];
foreach($arr as $k => $v){
$dump = var_export($v, true);
$last_comma_pos = strrpos($dump,",");
$cleared_value = substr_replace($dump, "", $last_comma_pos, 1);
$strings[] = $k.": ".$cleared_value;
}
/*****************/
// Now $strings variable contains all the needed strings
echo "<pre>";
foreach($strings as $str){
echo $str . "\n";
}
// the output:
0: array (
'name' => 'John',
'username' => 'Doe'
)
1: array (
'name' => 'Mike',
'username' => 'Tyson'
)
My "main" array looks like this - var_dump($main)
[zlec_addresoperator] => and
[filtervalue0] => Test
[filtercondition0] => CONTAINS
[filteroperator0] => 1
[filterdatafield0] => zlec_addres
[zlec_nroperator] => and
[filtervalue1] => SecondVal
[filtercondition1] => CONTAINS
[filteroperator1] => 1
[filterdatafield1] => zlec_nr
I want to build a new array as
array( filterdatafield0 = > filtervalue0 , filterdatafield1 = > filtervalue1)
etc
First of all I decided to filter out what I wan't with the following codes. Creating new arrays to keep the data I wan't, so $arraykeys will contain the filterdatafield.{1,2} values. In this case it will be zlec_addres and zlec_nr.
The second $arrayvalue will keep the filtervalue.{1,2} which is the value for the filter.
$newarray = array();
$arraykeys = array();
$arrayvalue = array();
foreach($_GET as $key => $value):
if(preg_match("/^filterdatafield.{1,2}$/",$key)>0) {
// $key is matched by the regex
$arrayvalue[] = $value;
}
if(preg_match("/^filtervalue.{1,2}$/",$key)>0) {
// $key is matched by the regex
$arraykeys[] = $key;
}
endforeach;
foreach($arraykeys as $a){
$newarray[$a] = $arrayvalue;
}
So the desired output would be
array(
zlec_addres => 'Test', zlec_nr = 'SecondVal'
)
Now it is
array(12) {
["filtervalue0"]=>
array(12) {
[0]=>
string(11) "zlec_addres"
[1]=>
string(7) "zlec_nr"
...
}
["filtervalue1"]=>
array(12) {
[0]=>
string(11) "zlec_addres"
[1]=>
string(7) "zlec_nr"
...
}
$newarray = array();
$arraykeys = array();
$arrayvalue = array();
foreach($_GET as $key => $value){
if(preg_match("/^filterdatafield.{1,2}$/",$key)>0) {
// $key is matched by the regex
$arraykeys[] = $value;
}
if(preg_match("/^filtervalue.{1,2}$/",$key)>0) {
// $key is matched by the regex
$arrayvalues[] = $value;
}
}
$newArray = array_combine($arraykeys, $arrayvalues);
This should work for you:
Just grab your keys which you want with preg_grep() and then array_combine() both arrays together.
<?php
$arr = [
"zlec_addresoperator" => "and",
"filtervalue0" => "Test",
"filtercondition0" => "CONTAINS",
"filteroperator0" => "1",
"filterdatafield0" => "zlec_addres",
"zlec_nroperator" => "and",
"filtervalue1" => "SecondVal",
"filtercondition1" => "CONTAINS",
"filteroperator1" => "1",
"filterdatafield1" => "zlec_nr",
];
$newArray = array_combine(
preg_grep("/^filterdatafield\d+$/", array_keys($arr)),
preg_grep("/^filtervalue\d+$/", array_keys($arr))
);
print_r($newArray);
?>
output:
Array
(
[filterdatafield0] => filtervalue0
[filterdatafield1] => filtervalue1
)
I have two string values namely $late_array and $wrong_array. The values are comma delimited.
What I would like to do is compare the two arrays and if the first two elements are the same add the value to the end else make it zero. The arrays I have:
$late_array = array(
[0] => 140610d,Richard,12
[1] => 140610a,Dave,22
[2] => 140610n,Noddy,121
[3] => 140610a,Nick,15
)
$wrong_array = array(
[0] => 140610d,Richard,2
[1] => 140610d,Mary,60
[2] => 140610a,Dave,11
[3] => 140610n,Noddy,90
)
The end result should be:
$combined_array = array(
[0] => 140610d,Richard,12,2
[1] => 140610d,Mary,0,60
[2] => 140610a,Dave,22,11
[3] => 140610a,Nick,15,0
[4] => 140610n,Noddy,121,90
)
I have so far formed a foreach and used the '===' operators to check if the date and name match then output as I want but I have not been able to get it to work if the name is not present in one array but another to make the value zero.
EDIT: Just to clear it up, hopefully. If the value is present in both arrays then the date,name,late value,wrong value should show. But if the value is present in late only then the value for wrong should be 0, same visa versa. Added "Nick" to try and explain a bit better.
This is what I did to solve the problem so far:
$wrong_val = array();
foreach($out as $wrong_value) {
$wrong_tosearch[] = substr($wrong_value,0,strrpos($wrong_value,","));
$w_id = substr($wrong_value,0,strrpos($wrong_value,","));
$wrong_val[$w_id] = substr($wrong_value,strrpos($wrong_value,",")+1,strlen($wrong_value));
}
foreach($sql_late_array as $late_value) {
$late_tosearch[] = substr($late_value,0,strrpos($late_value,","));
$l_id = substr($late_value,0,strrpos($late_value,","));
$late_val[$l_id] = substr($late_value,strrpos($late_value,",")+1,strlen($late_value));
}
$merge = array_merge($wrong_tosearch,$late_tosearch);
$sort = array_values(array_unique($merge));
$combined_array = array();
foreach ($sort as $search_val) {
if (array_key_exists($search_val,$wrong_val) !== FALSE) {
foreach ($wrong_val as $w_key=>$w_val) {
$combined_array[$w_key]['late'] = "0";
$combined_array[$w_key]['wrong'] = $w_val;
}
}
if (array_key_exists($search_val,$late_val) !== FALSE) {
foreach ($late_val as $l_key=>$l_val) {
$combined_array[$l_key]['wrong'] = "0";
$combined_array[$l_key]['late'] = $l_val;
}
}
}
print_r($combined_array);
Check if below code solves your problem.
$late_array = array(
"0" => "140610d,Richard,12",
"1" => "140610a,Dave,22",
"2" => "140610n,Noddy,121"
);
$wrong_array = array(
"0" => "140610d,Richard,2",
"1" => "140610d,Mary,60",
"2" => "140610a,Dave,11",
"3" => "140610n,Noddy,90"
);
foreach($wrong_array as $wv)
{
$tosearch = substr($wv,0,strrpos($wv,",")-1);
$valtoadd = substr($wv,strrpos($wv,",")+1,strlen($wv));
$added=false;
foreach($late_array as $lv)
{
if(strstr($lv, $tosearch) !== false)
{
$combined_array[] = $lv.",".$valtoadd;
$added=true;
break;
}
}
if(!$added)
$combined_array[] = $tosearch.",0,".$valtoadd;
}
$tcombined_array = $combined_array;
foreach($late_array as $wv)
{
$added = false;
foreach($tcombined_array as $cv)
if(strstr($cv,$wv))
$added = true;
if(!$added) $combined_array[] = $wv.",0";
}
print_r($combined_array);
May be big but works
<?php
$late_array = array(
0 => "140610d,Richard,12",
1 => "140610a,Dave,22",
2 => "140610n,Noddy,121",
);
$wrong_array = array(
0 => "140610d,Richard,2",
1 => "140610d,Mary,60",
2 => "140610a,Dave,11",
3 => "140610n,Noddy,90"
);
$pattern = "/[0-9]*[a-zA-Z]*,[0-9]*[a-zA-Z]*,/";
$combined_array = $late_array;
foreach($wrong_array as $wrong_index => $wrong_value){
foreach($late_array as $late_index => $late_value){
preg_match_all($pattern, $late_value, $late_matches);
preg_match_all($pattern, $wrong_value, $wrong_matches);
if($late_matches[0] == $wrong_matches[0]){
$explode = explode(',',$wrong_value);
$combined_array[$late_index] = $combined_array[$late_index].','.$explode[2];
$matchedValues[] = $wrong_index;
}
}
}
$unmatched_values = array_diff(array_keys($wrong_array), array_values($matchedValues));
foreach($unmatched_values as $key => $value){
$combined_array[] = $wrong_array[$value].',0';
}
echo '<pre>';
print_r($combined_array);
?>
Right now i got an array which has some sort of information and i need to create a table from it. e.g.
Student{
[Address]{
[StreetAddress] =>"Some Street"
[StreetName] => "Some Name"
}
[Marks1] => 100
[Marks2] => 50
}
Now I want to create database table like which contain the fields name as :
Student_Address_StreetAddress
Student_Address_StreetName
Student_Marks1
Student_Marks2
It should be recursive so from any depth of array it can create the string in my format.
You can use the RecursiveArrayIterator and the RecursiveIteratorIterator (to iterate over the array recursively) from the Standard PHP Library (SPL) to make this job relatively painless.
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
$keys = array();
foreach ($iterator as $key => $value) {
// Build long key name based on parent keys
for ($i = $iterator->getDepth() - 1; $i >= 0; $i--) {
$key = $iterator->getSubIterator($i)->key() . '_' . $key;
}
$keys[] = $key;
}
var_export($keys);
The above example outputs something like:
array (
0 => 'Student_Address_StreetAddress',
1 => 'Student_Address_StreetName',
2 => 'Student_Marks1',
3 => 'Student_Marks2',
)
(Working on it, here is the array to save the trouble):
$arr = array
(
'Student' => array
(
'Address' => array
(
'StreetAddress' => 'Some Street',
'StreetName' => 'Some Name',
),
'Marks1' => '100',
'Marks2' => '50',
),
);
Here it is, using a modified version of #polygenelubricants code:
function dfs($array, $parent = null)
{
static $result = array();
if (is_array($array) * count($array) > 0)
{
foreach ($array as $key => $value)
{
dfs($value, $parent . '_' . $key);
}
}
else
{
$result[] = ltrim($parent, '_');
}
return $result;
}
echo '<pre>';
print_r(dfs($arr));
echo '</pre>';
Outputs:
Array
(
[0] => Student_Address_StreetAddress
[1] => Student_Address_StreetName
[2] => Student_Marks1
[3] => Student_Marks2
)
Something like this maybe?
$schema = array(
'Student' => array(
'Address' => array(
'StreetAddresss' => "Some Street",
'StreetName' => "Some Name",
),
'Marks1' => 100,
'Marks2' => 50,
),
);
$result = array();
function walk($value, $key, $memo = "") {
global $result;
if(is_array($value)) {
$memo .= $key . '_';
array_walk($value, 'walk', $memo);
} else {
$result[] = $memo . $key;
}
}
array_walk($schema, 'walk');
var_dump($result);
I know globals are bad, but can't think of anything better now.
Something like this works:
<?php
$arr = array (
'Student' => array (
'Address' => array (
'StreetAddress' => 'Some Street',
'StreetName' => 'Some Name',
),
'Marks1' => array(),
'Marks2' => '50',
),
);
$result = array();
function dfs($data, $prefix = "") {
global $result;
if (is_array($data) && !empty($data)) {
foreach ($data as $key => $value) {
dfs($value, "{$prefix}_{$key}");
}
} else {
$result[substr($prefix, 1)] = $data;
}
}
dfs($arr);
var_dump($result);
?>
This prints:
array(4) {
["Student_Address_StreetAddress"] => string(11) "Some Street"
["Student_Address_StreetName"] => string(9) "Some Name"
["Student_Marks1"] => array(0) {}
["Student_Marks2"] => string(2) "50"
}
function getValues($dataArray,$strKey="")
{
global $arrFinalValues;
if(is_array($dataArray))
{
$currentKey = $strKey;
foreach($dataArray as $key => $val)
{
if(is_array($val) && !empty($val))
{
getValues($val,$currentKey.$key."_");
}
else if(!empty($val))
{
if(!empty($strKey))
$strTmpKey = $strKey.$key;
else
$strTmpKey = $key;
$arrFinalValues[$strTmpKey]=$val;
}
}
}
}