PHP move bold text to array key - php

I have details array:
[info_details] => Array
(
[0] => <b>title:</b> this is title
[1] => <b>name:</b> this is name
[2] => <b>created</b> this is date
)
and I need to format this array to this:
[info_details] => Array
(
[title] => this is title
[name] => this is name
[created] => this is date
)
so what is the best way to explode bold text?
my code now:
foreach ( $array as $key => $value ) {
$this->__tmp_data['keep'][] = preg_split('/<b[^>]*>/', $value);
}
but it doesn't work.

PHP has inbuilt function strip_tags() to strip HTML tags.
foreach ( $array as $key => $value ) {
$this->__tmp_data['keep'][] = strip_tags($value);
}
UPDATE
<?php
$info_details = array
(
'<b>title:</b> this is title',
'<b>name:</b> this is name',
'<b>created:</b> this is date'
);
$tmp_data = [];
foreach ( $info_details as $key => $value ) {
list($key,$value)=explode('</b>', $value);
$tmp_data['keep'][str_replace(array(':','<b>'),'',$key)] = $value;
}
echo '<pre>';
print_r($tmp_data);
?>
OUTPUT
Array
(
[keep] => Array
(
[title] => this is title
[name] => this is name
[created] => this is date
)
)

Can try this regex with preg_match() and str_replace()
$pattern = "/<b>.+:<\/b>\s?/";
$arr['info_details'] = [
'<b>title:</b> this is title',
'<b>name:</b> this is name',
'<b>created:</b> this is date',
];
$new_arr['info_details'] = [];
foreach($arr['info_details'] as $val){
preg_match($pattern, $val, $m);
$new_arr['info_details'][trim(strip_tags($m[0]), ': ')] = str_replace($m[0], '', $val);
}
print '<pre>';
print_r($new_arr);
print '</pre>';
Output
Array
(
[info_details] => Array
(
[title] => this is title
[name] => this is name
[created] => this is date
)
)

Assuming that the colon will always be present you can use strip_tags and explode to get what you want.
<?php
$info_details = array(
"<b>title:</b> this is title",
"<b>name:</b> this is name",
"<b>created:</b> this is date"
);
$return = array();
foreach($info_details as $val){
list ($key, $value) = explode(":",strip_tags($val), 2);
$return[$key] = $value;
}
print_r($return);
See it live here. Also worth noting that this implementation will remove the : from the array key and strip any html content from the trailing portion of each array element.
If you can't rely on the delimiter to be there you can instead use the close bold tag as your delimiter.
<?php
$info_details = array(
"<b>title:</b> this is title",
"<b>name:</b> this is name",
"<b>created</b> this is date"
);
$return = array();
foreach($info_details as $val){
list ($key, $value) = explode("</b>",$val, 2);
$key = strip_tags($key);
$return[$key] = $value;
}
print_r($return);
or run it here

So I found a solution, but this is hardcode...
foreach ( $array as $key => $value ) {
$this->__tmp_data['keep'][strtolower(str_replace(':', '', strip_tags(#reset(explode('</b>', $value)))))] = trim(#end(explode('</b>', $value)));
}
any other solutions will be accepted, even regex are welcome!

reading above comments I guess this is what you needed.
<?php
$info_details = array
(
'<b>title:</b> this is title',
'<b>name:</b> this is name',
'<b>created:</b> this is date'
);
foreach ($info_details as $value)
{
$temp = explode("</b>",$value);
$info_details = array(strip_tags(str_replace(":","",$temp[0])) =>$temp[1]);
}
print_r($info_details);
?>

Related

Converting array with equals to associative array

I have the following array in PHP
array(
"lat = -0.47023808202763651",
"lon = -163.04466494518647",
"alt = 4263.5330573538085",
"hgt = 0.382990122",
"nrm = 0.0816367865,0.996595144,-0.0115590692",
"rot = 0.34263891,-0.470143765,0.647551596,0.492179215",
"CoM = 0,0,0",
"stg = 0"
)
How could I convert this to an associative array where the keys are what's before equals and the values are what's after the equals:
array(
"lat" => "-0.47023808202763651",
"lon" => "-163.04466494518647",
"alt" => "4263.5330573538085",
"hgt" => "0.382990122",
"nrm" => "0.0816367865,0.996595144,-0.0115590692",
"rot" => "0.34263891,-0.470143765,0.647551596,0.492179215",
"CoM" => "0,0,0",
"stg" => "0"
)
I have seen walking an array here: Explode a string to associative array But have been unable to convert using this method...
Any tips? Sample code?
You need to loop the array and explode it and create an new array with key and value
$new_array = array();
foreach( $array as $value ){
list($key,$value)=explode('=',$value);
$new_array[trim($key)] = trim($value);
}
print_r($new_array);
Out put:
Array
(
[lat] => -0.47023808202763651
[lon] => -163.04466494518647
[alt] => 4263.5330573538085
[hgt] => 0.382990122
[nrm] => 0.0816367865,0.996595144,-0.0115590692
[rot] => 0.34263891,-0.470143765,0.647551596,0.492179215
[CoM] => 0,0,0
[stg] => 0
)
function splitStringsToArray($array) {
$need = [];
foreach ($array as $v) {
list($key, $value) = explode(' = ', $v);
$need[$key] = $value;
}
return $need;
}
$arrayYouHave = array(
"lat = -0.47023808202763651",
"lon = -163.04466494518647",
"alt = 4263.5330573538085",
"hgt = 0.382990122",
"nrm = 0.0816367865,0.996595144,-0.0115590692",
"rot = 0.34263891,-0.470143765,0.647551596,0.492179215",
"CoM = 0,0,0",
"stg = 0"
);
$arrayYouNeed = splitStringsToArray($arrayYouHave);
print_r($arrayYouHave, $arrayYouNeed);

Convert an associative array to a simple of its values in php

I would like to convert the array:
Array
(
[0] => Array
(
[send_to] => 9891616884
)
[1] => Array
(
[send_to] => 9891616884
)
)
to
$value = 9891616884, 9891616884
Try this:
//example array
$array = array(
array('send_to'=>3243423434),
array('send_to'=>11111111)
);
$value = implode(', ',array_column($array, 'send_to'));
echo $value; //prints "3243423434, 11111111"
You can use array_map:
$input = array(
array(
'send_to' => '9891616884'
),
array(
'send_to' => '9891616884'
)
);
echo implode(', ', array_map(function ($entry) {
return $entry['tag_name'];
}, $input));
Quite simple, try this:
// initialize and empty string
$str = '';
// Loop through each array index
foreach ($array as $arr) {
$str .= $arr["send_to"] . ", ";
}
//removes the final comma and whitespace
$str = trim($str, ", ");

PHP: Convert a multidimensional array

Given the following array:
Array
(
[entity] => Array
(
[title] => Array
(
[empty] => error message
)
[link] => Array
(
[empty] => error message
)
[authors] => Array
(
[0] => Array
(
[full_name] => Array
(
[max_lengh] => another error message 2
)
)
)
)
)
How to convert it into a form like:
$array = [
'entity[title]' => 'error message',
'entity[link]' => 'error message',
'entity[authors][0][full_name]' => 'another error message 2',
];
I think this is done via recursion or use the references but the two things I'm not good)
Thanking you in advance!
You are totally mixed up about array syntax. There is no reason you would want an array like that. Only point to make is that the [empty] becomes [0], you might try var_export to show it better.
What is this for?
$array = [
'entity[title]' => 'error message',
'entity[link]' => 'error message',
'entity[authors][0][full_name]' => 'another error message 2',
];
What even is it...? You have the [] inside the quotes. I mean, you could do very easily
$array2['title'] = $array['title'][0];
etc.
Another thing to address, why you have it like that in the first place?
Anyway, it should work something like this.
foreach ($array as $key => $value)
{
if (isset($value[0]) && !is_array($value[0]))
{
$array[$key] = $value[0];
}
}
Maybe not properly explained to the task.
Thanks to all.
function format(array $array, $withLastKey = false) {
$iterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator($array));
$returnArray = [];
foreach ($iterator as $key => $value) {
$keys = [];
for ($i = $iterator->getDepth(); $i >= 0; $i--) {
$childKey = $iterator->getSubIterator($i)->key();
// if first element then without bracket
$keys[] = ($i == 0) ? $childKey : '[' . $childKey . ']';
}
$keys = array_reverse($keys);
($withLastKey) ?: array_pop($keys);
$returnArray[implode('', $keys)] = $value;
}
return $returnArray;
}

Find values in multidimensional arrays

I've a multidimensional array:
array (
array (
"username" => "foo",
"favoriteGame" => "Mario"
)
array (
"username" => "bar",
"favoriteGame" => "Mario"
)
array (
"username" => "xyz",
"favoriteGame" => "Zelda"
)
)
How could I get the usernames of the persons that like to play for example Mario the easiest way possible?
EDIT:
My fault: forget to explicitly mention that the "favoriteGame" value is dynamic and I cannot know which it is in advance.
My Solution:
foreach($users as $key => $value)
{
if(!isset($$value['favoriteGame']))
{
$$value['favoriteGame'] = array();
}
array_push($$value['favoriteGame'], $value['username']);
}
Iterate over each sub-array and find its favoriteGame value.
If there is not already an array $favoriteGame create it.
Push the username-value of the actual sub-array to the $favoriteGame array.
Thanks for your replies, I just couldn't phrase this question properly.
function getUsernamesByFavoriteGame($data, $game) {
$usernames = array();
foreach($data as $arr) {
if ($arr['favoriteGame'] == $game) {
$usernames[] = $arr['username'];
}
}
return $usernames;
}
$usernames = array();
foreach($array as $key => $value) {
if ($value['favoriteGame'] == 'Mario') {
$usernames[] = $value['username'];
}
}
I would use array_filter. If you have PHP 5.3 or up, you can do it like this:
$favorite = "Mario";
$filter = function($player) use($favorite) { return $player['favoriteGame'] == $favorite; };
$filtered = array_filter($players, $filter);
It will be a little different for older versions because you won't be able to use lambda functions.
$game = 'Mario';
$users = array();
foreach($array as $key => $value) {
if ($value['favoriteGame'] == $game) {
$users[] = $value['username'];
}
}
If you are using this more often then convert the data structure to something like this.
array(
"Mario" => array(
"0":"foo",
"1":"xyz"
)
"Zelda" => array(
"0":"pqr",
"1":"abc"
)
)
This will directly give you list of user names for a favorite game.
$arr[$favGame]
If you cannot change the data structure then go with with tigrang has suggested.
I think you should implement a custom multidimensional search function.
Take a look at this answer.
Here's how you would use it
Code | Live example
function search($array, $key, $value){
$results = array();
if (is_array($array))
{
if (isset($array[$key]) && $array[$key] == $value)
$results[] = $array;
foreach ($array as $subarray)
$results = array_merge($results, search($subarray, $key, $value));
}
return $results;
}
$arr = array (
array (
"username" => "foo",
"favoriteGame" => "Mario"
),
array (
"username" => "bar",
"favoriteGame" => "Mario"
),
array (
"username" => "xyz",
"favoriteGame" => "Zelda"
)
);
print_r(search($arr, 'favoriteGame', 'Mario'));
//OUTPUT
Array (
[0] => Array (
[username] => foo
[favoriteGame] => Mario
)
[1] => Array (
[username] => bar
[favoriteGame] => Mario
)
)
$array = array( 'a' => 'A',
'b'=>'B',
'c'=>'C',
'd'=>array(
'e'=>array(
'f'=>'D'
),
'g'=>array(
'h'=>'E'
)
),
'i'=>'F',
'j'=>array(
'k'=>'G'
),
'l'=>'H'
);
$new_array = array();
foreach($array as $k1=>$v1){
if(is_array($v1)){
$new_array = parseArray($new_array, $k1, $v1);
}else{
$new_array = array_merge($new_array, array($k1=>$v1));
}
}
function parseArray($new_array, $key, $val){
if(is_array($val)){
foreach($val as $k2=>$v2){
if(is_array($v2)){
$new_array = parseArray($new_array, $k2, $v2);
}else{
$new_array = array_merge($new_array, array($k2=>$v2));
}
}
}else{
$new_array = array_merge($new_array, array($key=>$val));
}
return $new_array;
}
Output
Array
(
[a] => A
[b] => B
[c] => C
[f] => D
[h] => E
[i] => F
[k] => G
[l] => H
)

Taking a string of period separated properties and converting it to a json object in php

I'm fairly sure I'm missing something blindingly obvious here but here it goes.
I am working on updating a search function in an application which was running a loop and doing a very large number of sql queries to get object / table relations to one large query that returns everything. However the only way I could think to return relations was period separated, what I am now wanting to do is take the flat array of keys and values and convert it into an associative array to then be jsonified with json_encode.
For example what I have is this...
array(
"ID"=>10,
"CompanyName"=>"Some Company",
"CompanyStatusID"=>2,
"CompanyStatus.Status"=>"Active",
"addressID"=>134,
"address.postcode"=>"XXX XXXX",
"address.street"=>"Some Street"
);
And what I want to turn it into is this...
array(
"ID"=>10,
"CompanyName"=>"Some Company",
"CompanyStatusID"=>2,
"CompanyStatus"=>array(
"Status"=>"Active"
),
"addressID"=>134,
"address"=>array(
"postcode"=>"XXX XXXX",
"street"=>"Some Street"
)
);
Now I'm sure this should be a fairly simple recursive loop but for the life of me this morning I can't figure it out.
Any help is greatly appreciated.
Regards
Graham.
Your function was part way there mike, though it had the problem that the top level value kept getting reset on each pass of the array so only the last period separated property made it in.
Please see updated version.
function parse_array($src) {
$dst = array();
foreach($src as $key => $val) {
$parts = explode(".", $key);
if(count($parts) > 1) {
$index = &$dst;
$i = 0;
$count = count($parts)-1;
foreach(array_slice($parts,0) as $part) {
if($i == $count) {
$index[$part] = $val;
} else {
if(!isset($index[$part])){
$index[$part] = array();
}
}
$index = &$index[$part];
$i++;
}
} else {
$dst[$parts[0]] = $val;
}
}
return $dst;
}
I am sure there is something more elegant, but quick and dirty:
$arr = array(
"ID"=>10,
"CompanyName"=>"Some Company",
"CompanyStatusID"=>2,
"CompanyStatus.Status"=>"Active",
"addressID"=>134,
"address.postcode"=>"XXX XXXX",
"address.street"=>"Some Street"
);
$narr = array();
foreach($arr as $key=>$val)
{
if (preg_match("~\.~", $key))
{
$parts = split("\.", $key);
$narr [$parts[0]][$parts[1]] = $val;
}
else $narr [$key] = $val;
}
$arr = array(
"ID" => 10,
"CompanyName" => "Some Company",
"CompanyStatusID" => 2,
"CompanyStatus.Status" => "Active",
"addressID" => 134,
"address.postcode" => "XXX XXXX",
"address.street" => "Some Street",
"1.2.3.4.5" => "Some nested value"
);
function parse_array ($src) {
$dst = array();
foreach($src as $key => $val) {
$parts = explode(".", $key);
$dst[$parts[0]] = $val;
if(count($parts) > 1) {
$index = &$dst[$parts[0]];
foreach(array_slice($parts, 1) as $part) {
$index = array($part => $val);
$index = &$index[$part];
}
}
}
return $dst;
}
print_r(parse_array($arr));
Outputs:
Array
(
[ID] => 10
[CompanyName] => Some Company
[CompanyStatusID] => 2
[CompanyStatus] => Array
(
[Status] => Active
)
[addressID] => 134
[address] => Array
(
[street] => Some Street
)
[1] => Array
(
[2] => Array
(
[3] => Array
(
[4] => Array
(
[5] => Some nested value
)
)
)
)
)

Categories