I want to convert a big yaml file to PHP array source code. I can read in the yaml code and get back a PHP array, but with var_dump($array) I get pseudo code as output. I would like to print the array as valid php code, so I can copy paste it in my project and ditch the yaml.
You're looking for var_export.
You could use var_export, serialize (with unserialize on the reserving end), or even json_encode (and use json_decode on the receiving end). The last one has the advantage of producing output that can be processed by anything that can handle JSON.
Don't know why but I could not find satisfying code anywhere.
Quickly wrote this. Let me know if you find any errors.
function printCode($array, $path=false, $top=true) {
$data = "";
$delimiter = "~~|~~";
$p = null;
if(is_array($array)){
foreach($array as $key => $a){
if(!is_array($a) || empty($a)){
if(is_array($a)){
$data .= $path."['{$key}'] = array();".$delimiter;
} else {
$data .= $path."['{$key}'] = \"".htmlentities(addslashes($a))."\";".$delimiter;
}
} else {
$data .= printCode($a, $path."['{$key}']", false);
}
}
}
if($top){
$return = "";
foreach(explode($delimiter, $data) as $value){
if(!empty($value)){
$return .= '$array'.$value."<br>";
}
};
return $return;
}
return $data;
}
//REQUEST
$x = array('key'=>'value', 'key2'=>array('key3'=>'value2', 'key4'=>'value3', 'key5'=>array()));
echo printCode($x);
//OUTPUT
$array['key'] = 'value';
$array['key2']['key3'] = 'value2';
$array['key2']['key4'] = 'value3';
$array['key2']['key5'] = array();
Hope this helps someone.
An other way to display array as code with indentation.
Tested only with an array who contain string, integer and array.
function bo_print_nice_array($array){
echo '$array=';
bo_print_nice_array_content($array, 1);
echo ';';
}
function bo_print_nice_array_content($array, $deep=1){
$indent = '';
$indent_close = '';
echo "[";
for($i=0; $i<$deep; $i++){
$indent.=' ';
}
for($i=1; $i<$deep; $i++){
$indent_close.=' ';
}
foreach($array as $key=>$value){
echo "<br>".$indent;
echo '"'.$key.'" => ';
if(is_string($value)){
echo '"'.$value.'"';
}elseif(is_array($value)){
bo_print_nice_array_content($value, ($deep+1));
}else{
echo $value;
}
echo ',';
}
echo '<br>'.$indent_close.']';
}
Related
I need to turn each end-point in a multi-dimensional array (of any dimension) into a row containing the all the descendant nodes using PHP. In other words, I want to resolve each complete branch in the array. I am not sure how to state this more clearly, so maybe the best way is to give an example.
If I start with an array like:
$arr = array(
'A'=>array(
'a'=>array(
'i'=>1,
'j'=>2),
'b'=>3
),
'B'=>array(
'a'=>array(
'm'=>4,
'n'=>5),
'b'=>6
)
);
There are 6 end points, namely the numbers 1 to 6, in the array and I would like to generate the 6 rows as:
A,a,i,1
A,a,j,2
A,b,2
B,a,m,3
B,a,n,4
B,b,2
Each row contains full path of descendants to the end-point. As the array can have any number of dimensions, this suggested a recursive PHP function and I tried:
function array2Rows($arr, $str='', $out='') {
if (is_array($arr)) {
foreach ($arr as $att => $arr1) {
$str .= ((strlen($str)? ',': '')) . $att;
$out = array2Rows($arr1, $str, $out);
}
echo '<hr />';
} else {
$str .= ((strlen($str)? ',': '')) . $arr;
$out .= ((strlen($out)? '<br />': '')) . $str;
}
return $out;
}
The function was called as follows:
echo '<p>'.array2Rows($arr, '', '').'</p>';
The output from this function is:
A,a,i,1
A,a,i,j,2
A,a,b,3
A,B,a,m,4
A,B,a,m,n,5
A,B,a,b,6
Which apart from the first value is incorrect because values on some of the nodes are repeated. I have tried a number of variations of the recursive function and this is the closest I can get.
I will welcome any suggestions for how I can get a solution to this problem and apologize if the statement of the problem is not very clear.
You were so close with your function... I took your function and modified is slightly as follows:
function array2Rows($arr, $str='', $csv='') {
$tmp = $str;
if (is_array($arr)) {
foreach ($arr as $att => $arr1) {
$tmp = $str . ((strlen($str)? ', ': '')) . $att;
$csv = array2Rows($arr1, $tmp, $csv);
}
} else {
$tmp .= ((strlen($str)? ', ': '')) . $arr;
$csv .= ((strlen($csv)? '<br />': '')) . $tmp;
}
return $csv;
}
The only difference is the introduction of a temporary variable $tmp to ensure that you don't change the $str value before the recursion function is run each time.
The output from your function becomes:
This is a nice function, I can think of a few applications for it.
The reason that you are repeating the second to last value is that in your loop you you are appending the key before running the function on the next array. Something like this would work better:
function array2Rows($arr, &$out=[], $row = []) {
if (is_array($arr)) {
foreach ($arr as $key => $newArray) {
if (is_array($newArray)) {
$row[] = $key; //If the current value is an array, add its key to the current row
array2Rows($newArray, $out, $row); //process the new value
} else { //The current value is not an array
$out[] = implode(',',array_merge($row,[$key,$newArray])); //Add the current key and value to the row and write to the output
}
}
}
return $out;
}
This is lightly optimized and utilizes a reference to hold the full output. I've also changed this to use and return an array rather than strings. I find both of those changes to make the function more readable.
If you wanted this to return a string formatted similarly to the one that you have in your function, replace the last line with
return implode('<br>', $out);
Alternatively, you could do that when calling, which would be what I would call "best practice" for something like this; e.g.
$result = array2Rows($arr);
echo implode('<br>', $result);
Note, since this uses a reference for the output, this also works:
array2Rows($arr, $result);
echo implode('<br>', $result);
I have this array of objects:
$table=[{"count":"2","id_f":"2255"},{"count":"6","id_f":"5886"}];
I want to get the value of id_f of each object and check if this value exist in another array ,I tried with this but it gives me the wrong result:
foreach($table as $t){
if (in_array($t[$id_f],$array){
//dosomething}
}else{
//do something else
}
}
I also tried with this:
foreach($table as $t){
if (in_array($t->$id_f,$array){
//dosomething}
}else{
//do something else
}
}
I can't get the right result , I will appreciate any help.
Another approach without foreach loop:
<?php
$table=json_decode('[{"count":"2","id_f":"2255"},{"count":"6","id_f":"5886"}]');
$data = [10, 20, 2255];
array_walk($table, function($obj) use (&$data) {
if (in_array($obj->id_f, $data)) {
echo "+";
} else {
echo "-";
}
});
The output obviously is:
+-
You dont show a json_decode() anywhere in your code, thats the first thing to do with a JSON String, to decode it into a PHP data structure. In this case an array of objects.
$other_array = array('2255', '9999');
$table='[{"count":"2","id_f":"2255"},{"count":"6","id_f":"5886"}]';
$array = json_decode($table);
foreach ( $array as $obj ) {
if (in_array($obj->id_f, $other_array)) {
echo 'Found one ' . $obj->id_f . PHP_EOL;
} else {
echo 'No match for ' . $obj->id_f . PHP_EOL;
}
}
Results
Found one 2255
No match for 5886
There's no need for the dollar sign before your Object property name (actually, it won't work, except of course if $id_f is a real variable which has for value 'id_f', but somehow I doubt it) :
foreach ($table as $t) {
if (in_array($t->id_f, $array){
// do something
} else {
// do something else
}
}
it can be done like this:
to define the object array you can define like below with json string approach. or to define object is like this $table = new stdClass();
<?php
$table='[{"count":"2","id_f":"2255"},{"count":"6","id_f":"5886"}]';
$obj = json_decode($table);
$array=array("2555","2255");
foreach($obj as $t){
if (in_array($t->id_f,$array)){
//dosomething
}else{
//do something else
}
}
?>
I'm trying to convert JSON-Object like [{"text":"hallo"},{"text":"hello"}] into a string which should look like "hallo hello".
At the moment, I'm decoding the JSON-Object with json_decode($words, true);
The result is being sent to a function than, which looks like:
function assocToString($assoc)
{
$ergString="";
foreach($assoc as $key => $value)
{
if($ergString=="")
{
$ergString = $value;
}
else
{
$ergString .= $value;
}
$ergString .= " ";
}
return $ergString;
}
I get errors like "Array to string conversion" all the time, maybe someone of you could please as be as kind as to help me out?
This apparently mean that your array was an multi-dimension array. Try to put another foreach loop inside the existing one.
Use vardump or print_r to check how does the current data store in $assoc look like
foreach($assoc as $key)
{
foreach($key as $value){
if($ergString=="")
{
$ergString = $value;
}
else
{
$ergString .= $value;
}
$ergString .= " ";
}
}
Try this see wether working
I'm currently using this:
foreach($hash_list as $key => $val){
if(in_array($search_this,$hash_list[$key])){
echo 'Found value in key '.$key;
break;
}
}
To find $search_this in this:
$hash_list = array();
$hash_list["a"] = array("dfv8p","hi8o7","d2l9f","qhx13","c7duz");
$hash_list["b"] = array("pdsyt","jjivh","nj12b","19tm2","ltsqp");
$hash_list["c"] = array("67s6q","tlwu7","c9p77","7airj","j7tej");
Is there a better way to find the key for this situation? $hash_list has about 500 arrays with 5 elements each inside.
Deadpool: #Sergey No php built-in function that I'm missing?
I dont think so. But I think it's may be little faster, but I'm not sure
$hash_list = array();
$hash_list["a"] = "dfv8p, hi8o7, d2l9f, qhx13, c7duz";
$hash_list["b"] = "pdsyt, jjivh, nj12b, 19tm2, ltsqp";
$hash_list["c"] = "67s6q, tlwu7, c9p77, 7airj, j7tej";
foreach($hash_list as $key => $val){
if(strpos($hash_list[$key], $search_this) !== false) {
echo 'Found value in key '.$key;
break;
}
}
You can use user build functions like this
function isValueExist($hash_list,$needle){
foreach($hash_list as $val){
if(in_array($needle,array_values($val))) return 1;
}
}
Usage :-
if (isValueExist($hash_list,"d2l9f")){
//DO you things here
}
You can make use of list() too ;)
<?php
$hash_list = array();
$hash_list["a"] = array("dfv8p","hi8o7","d2l9f","qhx13","c7duz");
$hash_list["b"] = array("pdsyt","jjivh","nj12b","19tm2","ltsqp");
$hash_list["c"] = array("67s6q","tlwu7","c9p77","7airj","j7tej");
$searchParam = "67s6q";
while(list($a,$b) = each($hash_list))
{
if(in_array($searchParam,$b))
{
echo "$searchParam found in $a\n";
}
}
OUTPUT :
67s6q found in c
I've been trying to get this to work and while I have tried many methods posted on this site on other pages, I can't get any of them to work.
I need to identify the last key so that my results don't have a , at the end. This sounds like such and easy task but I just cant seem to get it to work! At this point I'm guessing I've just had a typo or something that I overlooked. Any help would be greatly appreciated.
This is what I have:
<?php
$searchString = $_GET["s"];
$prefix = 'http://link_to_my_xml_file.xml?q=';
$suffix = '&resultsPerPage=100';
$file = $prefix . $searchString . $suffix;
if(!$xml = simplexml_load_file($file))
exit('False'.$file);
foreach($xml->results->result as $item) {
echo $item->sku . ",";
}
?>
Now this works just fine, it just has a , at the end:
12345,23456,34567,45678,
For reference my xml file is laid out like: results->result->sku, but with a lot more mixed in. I'm just singling out the fields.
Consider identifying the first instead?
$first = true;
foreach($xml->results->result as $item) {
if ($first) {
$first = false;
} else {
echo ',';
}
echo $item->sku;
}
Use rtrim()
foreach($xml->results->result as $item) {
$mystr .= $item->sku . ",";
}
echo rtrim($mystr, ",")
Should output:
12345,23456,34567,45678
Demo!
If your keys are in numerical order like: 0, 1, 2, 3 etc this could be a solution:
foreach($xml->results->result as $key => $item)
{
if( $key > 0 ) echo ", ";
echo $item->sku
}
Possible solution #1:
$first = true;
foreach ($xml->results->result as $item) {
if ($first) {
$first = false;
} else {
echo ', ';
}
echo $item->sku;
}
Possible solution #2:
$items = array();
foreach ($xml->results->result as $item) {
$items[] = $item->sku;
}
echo join(', ', $items);
You can just put everything in a string and then run:
substr($yourstr, 0, -1);
on your code to remove the last character:
http://de1.php.net/manual/en/function.substr.php
Or get the total number of entries in your array and count your position