This question already has answers here:
array_walk_recursive to apply function to each array element not working at all
(3 answers)
Closed 4 months ago.
I have a string in encoded array format. What I want is to replace the curly bracket in its value only. I have tried like this
$str = '[{"id":"{3e71209}","elType":"section","settings":[],"elements":[{"id":"70e5fb7","elType":"column","settings":{"_column_size":100,"_inline_size":null},"elements":[{"id":"70e09a1","elType":"widget","settings":{"title":"{title1|title2|title3}"},"elements":[],"widgetType":"heading"}],"isInner":false}],"isInner":false}]';
echo 'str asli: '.$str;
echo '<br><br>';
$strOlah = str_replace("{", "xx", json_decode($str));
echo 'str olah: '. json_encode($strOlah);
it's resulting the exact str. nothing change.
My expected result is the str become like this
[{"id":"xx3e71209}","elType":"section","settings":[],"elements":[{"id":"70e5fb7","elType":"column","settings":{"_column_size":100,"_inline_size":null},"elements":[{"id":"70e09a1","elType":"widget","settings":{"title":"xxtitle1|title2|title3}"},"elements":[],"widgetType":"heading"}],"isInner":false}],"isInner":false}]
How to do that without looping through an array because the structure and key of the array are very dynamic.
You need to loop through the array, calling str_replace() on the specific object properties.
$array = json_decode($str);
foreach ($array as $obj) {
$obj->id = str_replace("{", "xx", $obj->id);
foreach ($obj->elements as $el1) {
foreach ($el1->elements as $el2) {
$el2->settings->title = str_replace("{", "xx", $el2->settings->title);
}
}
}
echo 'str olah: ' . json_encode($array);
Related
This question already has answers here:
PHP - Convert multidimensional array to 2D array with dot notation keys
(5 answers)
Closed 2 years ago.
I have a little problem. I want to transform this:
$array['page']['article']['header'] = "Header";
$array['page']['article']['body'] = "Body";
$array['page']['article']['footer'] = "Footer";
$array['page']['news']['header'] = "Header";
$array['page']['news']['body'] = "Body";
$array['page']['news']['footer'] = "Footer";
Into this:
$array['page.article.header'] = "Header";
$array['page.article.body'] = "Body";
$array['page.article.footer'] = "Footer";
$array['page.news.header'] = "Header";
$array['page.news.body'] = "Body";
$array['page.news.footer'] = "Footer";
The number of dimensions is variable and can be times 0 or 10. I don't know if I used the right search term, but Google could not help me so far.
So if someone has a solution for me.
Thanks
You can loop over the array at hand. Now, if the current value is an array, recursively call that array to the function call. On each function call, return an array with key value pairs. When you get the output from your sub-array, attach current key value to all keys of that sub-array returned output.
Snippet:
<?php
function rearrange($array){
$output = [];
foreach($array as $key => $val){
if(is_array($val)){
$out = rearrange($val);
foreach($out as $sub_key => $sub_val){
$output[$key . "." . $sub_key] = $sub_val;
}
}else{
$output[$key] = $val;
}
}
return $output;
}
print_r(rearrange($array));
Demo: https://3v4l.org/40hjK
This question already has answers here:
Read the longest string from an array in PHP 5.3
(3 answers)
Closed 2 years ago.
$array =array("AB","ABC","ABCD","ABCDE","BD");
Requirement: find the longest element in the array
Output:ABCDE
$array =array("AB","ABC","ABCD","ABCDE","BD");
$longstring = $array[0];
foreach( $array as $string ) {
if ( strlen( $string ) > strlen( $longstring ) ) {
$longstring = $string;
}
}
echo $longstring;
First we are iterate the array with help of foreach loop. in foreach loop we check $result is less than array value. if array value is greater then $result array then we override previous value of $result with new value. if we found greatest length than previous array element then we are storing new length & key of new element in variable.
$array =array("AB","ABC","ABCD","ABCDE","BD");
$result = $resultkey = 0;
foreach($array as $key=>$value) {
if($result < strlen($value) ) {
$result = strlen($value);
$resultkey = $key;
}
}
echo 'longest value:' $result;
echo 'result :' $array[$resultkey]
Output:
longest value: 5
result :ABCDE
You could sort the array by string length using strlen and usort and get the first item:
$array =array("AB","ABC","ABCD","ABCDE","BD");
usort($array, function($x, $y) { return strlen($y)-strlen($x); });
echo $array[0];
Result:
ABCDE
Demo
Try this, though it's a bit confusing.
<?php //php 7.0.8
$array = array("AB","ABC","ABCD","ABCDE","BD");
$longertext = array_search(max($array), $array)-1; //4-1 =3
// minus 1 because it's counting the actual position not starts with 0 it returns 4
echo $longertext; //equals 3
echo "\n";
echo $array[$longertext]; //equals ABCDE
?>
The actual test: http://rextester.com/OTI23127
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 5 years ago.
I have result
{"success":true,"data":{"id":6583879,"listingId":"11745/3470/OMS"}}
I need to explode it on two arrays:
$id = 6583879;
and
$listid = 11745/3470/OMS
I'd like to avoid counting characters, this response may be another in future. I was thinking about taking:
everything between "id": and comma
everything between "listingId":" and "
PHP code demo
<?php
$json='{"success":true,"data":{"id":6583879,"listingId":"11745/3470/OMS"}}';
$array= json_decode($json,true);
extract($array["data"]);
$first=array("id"=>$id);
$second=array("listingId"=>$listingId);
print_r($first);
print_r($second);
Output:
Array
(
[id] => 6583879
)
Array
(
[listingId] => 11745/3470/OMS
)
just decode the json data
$data = '{"success":true,"data":[{"id":6583879,"listingId":"11745/3470/OMS"}]}';
$arr = json_decode($data);
$id = array();
$listing = array();
for($i=0; $i < count($arr->data); $i++){
$id[$i] = $arr->data[$i]->id;
$listing[$i] = $arr->data[$i]->listingId;
}
//loop array to view data
foreach($id as $value){
echo $value.'<br>';
}
?>
<?php
$json='{"success":true,"data":{"id":6583879,"listingId":"11745/3470/OMS"}}';
$decoded = json_decode($json);
$id = $decoded['data']['id'];
$listingId = $decoded['data']['listingId'];
This question already has answers here:
Convert backslash-delimited string into an associative array
(4 answers)
Closed 6 years ago.
I have the following string which I've managed to get cleaned up into a clear format:
string(191) "twitter:3 facebookshare_count:5 like_count:0 comment_count:0 total_count:8 click_count:5 buffer:0 pinterest:0 linkedin:0 stumbleupon:0 redditscore:0 ups:8 downs:3 google:4 delicious:0 digg:0 "
I am now trying to take this and create an array so each digit is associated with its platform.
$shares = array(
'twitter' => 3,
'facebookshare_count' => 5,
'like_count' => 0
)
and so on...
I've been looking at the explode function, using spaces as the delimiter, but I'm really stuck on how to achieve this end result.
I am relatively new to PHP, and struggling to find the words to use to search for this problem. I don't know if 'array' or 'object' is even the right terminology here.
$str = 'twitter:3 facebookshare_count:5 like_count:0 comment_count:0 total_count:8 click_count:5 buffer:0 pinterest:0 linkedin:0 stumbleupon:0 redditscore:0 ups:8 downs:3 google:4 delicious:0 digg:0';
$strArray = explode(' ', $str);
$desiredArray = [];
foreach ($strArray as $value) {
$value = explode(":", $value);
$desiredArray[$value[0]] = $value[1];
}
$myString = "twitter:3 facebookshare_count:5 like_count:0 comment_count:0 total_count:8 click_count:5 buffer:0 pinterest:0 linkedin:0 stumbleupon:0 redditscore:0 ups:8 downs:3 google:4 delicious:0 digg:0";
$parseString = explode(" ", $myString);
$newArray = [];
foreach($parseString as $item) {
$splitItem = explode(":", $item);
$newArray[$splitItem[0]] = $splitItem[1];
}
foreach($newArray as $key=>$data) {
echo $key . " " . $data . "<br>";
}
Hope it helps !!!
This question already has answers here:
Imploding an associative array in PHP
(10 answers)
Closed 8 years ago.
I have a named array that look like this:
$arr = array('name'=>'somename','value'=>'somevalue');
I want to turn that array into something like this:
name='somename' value='somevalue'
I tried http_build_query() to do it.
echo http_build_query($arr, '', ' ');
But this is the result I get:
name=somename%21 value=somevalue%21
How can I get the result I want with http_build_query()? Or, is there any PHP function to do it?
Thank you.
http_build_query returns a urlencoded string. If you don't want that you can run it through urldecode
$arr = array('name'=>"'somename'",'value'=>"'somevalue'");
print urldecode(http_build_query($arr,null,' '));
Try with foreach()
$arr = array('name'=>'somename','value'=>'somevalue');
$str = '';
foreach($arr as $k=>$v) {
$str.= "$k='$v' ";
}
echo $str;
foreach ($array as $key => $value) {
$result .= "$key='$value' ";
}
echo rtrim($result,' ');