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
Related
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 have this line
foreach($giftmessage as $key=>$value) {
$giftmessagearray['order_giftmessage_'.$key] = $value;
}
I want to add somewhere in the middle (I guess before the $key or the $value?) something that will print to my template.
I have tried this:
foreach($giftmessage as $key=>$value) {
$customtext = "something to echo there";
$giftmessagearray['order_giftmessage_'. $customtext .$key] = $value;
}
But it doesn't work, actually it breaks my query.
I have an json array like given below, what I want is to
parse through the array and get a value for corresponding
key .Eg SubAdministrativeAreaName .I could have parsed it
like .
["AddressDetails"]['Country']['AdministrativeArea'] ['SubAdministrativeArea']['SubAdministrativeAreaName']
but the structure of array is not fixed , it may contain some other
keys within which "SubAdmininstrativeArea" may be enclosed .
What I want is a php function that will search for a particular key
name through multidimensional json array of any depth .
Any help would be appreciated .
"AddressDetails": {
"Accuracy": 6,
"Country": {
"AdministrativeArea": {
"AdministrativeAreaName": "Maharashtra",
"SubAdministrativeArea": {
"SubAdministrativeAreaName": "Parbhani",
"Thoroughfare": {
"ThoroughfareName": "SH217"
}
}
},
"CountryName": "India",
"CountryNameCode": "IN"
}
}
OK, different answer based on comment below:
function array_key_search_deep($needle, $haystack) {
$value = NULL;
if(isset($haystack[$needle])) {
$value = $haystack[$needle];
} else {
foreach($haystack as $node) {
if(is_array($node)) {
$value = array_key_search_deep($needle, $node);
if(!is_null($value)) {
break;
}
}
}
}
return $val;
}
Old Answer
This will allow you to traverse an unknown path in any array tree:
$path = array('AddressDetails', 'Country', 'AdministrativeArea', 'SubAdministrativeArea', 'SubAdministrativeAreaName');
$node = $json_object;
foreach($path as $path_index) {
if(isset($node[$path_index])) {
$node = $node[$path_index];
} else {
$node = NULL;
}
}
echo($node);
Thanks guys , what I made was a a solution like this
I finally found a simple solution myself
For eg) To get "ThoroughfareName" make a call
recursive_array_search($json_array,'ThoroughfareName') ;
function recursive_array_search($arr,$jackpot)
{
foreach ($arr as $key => $value)
{
if(is_array($value))
{
$val=recursive_array_search($value,$jackpot) ;
return $val;
}
else
{
if($key==$jackpot)
return $value;
}
}
}
You could use JSONPath (XPath for JSON)
http://goessner.net/articles/JsonPath/
(with for instance the expression "$..SubAdministrativeAreaName")
EDIT: Haven't tested it, not sure how reliable it is.
I have a question about arrays and foreach.
If i have an array like this:
$test_arr = array();
$test_arr['name1'] = "an example sentence";
$test_arr['anything'] = "dsfasfasgsdfg";
$test_arr['code'] = "4334refwewe";
$test_arr['empty1'] = "";
$test_arr['3242'] = "";
how can I do a foreach and "pick" only the ones that have values? (in my array example, would only take the first 3 ones, name1, anything and code).
I tried with
foreach ($test_arr as $test) {
if (strlen($test >= 1)) {
echo $test . "<br>";
}
}
but it doesn't work. Without the "if" condition it works, but empty array values are taken into consideration and I don't want that (because I need to do a <br> after each value and I don't want a <br> if there is no value)
Sorry if I don't explain myself very well, I hope you understand my point. Shouldn't be too difficult I guess..
Thanks for your help !
Maybe will work
foreach ($test_arr as $test) {
if (strlen($test)!=="") {
echo $test . "<br>";
}
}
Your solution with corrected syntax:
foreach ($test_arr as $test) {
if (strlen($test)>=1) {
echo $test . "<br>";
}
}
Since empty strings are false, you could just do this (but you'd exclude 0's with the if):
foreach ($test_arr as $key => $val) {
if ($val) {
echo $val. "<br>";
}
}
If it has to be an empty string then (excluding 0 and FALSE):
foreach ($test_arr as $key => $val) {
// the extra = means that this will only return true for strings.
if ($val !== '' ) {
echo $val. "<br>";
}
}
Since it looks like you're using an associative array, you should be able to do this:
foreach( $test_arr as $key => $value )
{
if( $value != "" )
{
echo $value . "<br />";
}
}
As shown, you can test $value for an empty string directly. Since this is precisely the test you are trying to accomplish, I would hope that this would solve your problem perfectly.
On another note, this is pretty straight forward and should be very maintainable in the future when you've forgotten exactly what it was that you were doing!
You are better off to use a while loop like this:
while(list($test_key, $test_value) = each($test_arr))
{
if($test_value != "") { echo $test_value . "<br/>"; }
}
reset($test_arr);
If your array gets large, the while will be much faster. Even on small arrays, I have noticed a big difference in the execution time.
And if you really don't want the array key. You can just do this:
while(list(, $test_value) = each($test_arr))
{
if($test_value != "") { echo $test_value . "<br/>"; }
}
reset($test_arr);
You can check if the value is emtpy with empty().
Note that values like 0 or false are considered empty as well, so you might have to check for string length instead.
just a simple typing error:
foreach ($test_arr as $test) {
if (strlen($test) >= 1) {
echo $test . "<br>";
}
}
Try this:
foreach ($test_arr as $test) {
if (strlen($test) > 0) {
echo $test . "<br>";
}
}
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.']';
}