Getting array values into a string - php

I output a PHP object via a loop but withing this look I have a few nested arrays.
[categories] => Array
(
[0] => Array
(
[0] => Chinese
[1] => chinese
)
[1] => Array
(
[0] => Vietnamese
[1] => vietnamese
)
)
[phone] => 5123355555
I can get the phone like this:
$response->businesses[$x]->phone
How do I get categories (first value) into a string like this:
Chinese, Vietnamese

You can achieve with array_column() :
$newArray = array_column($response->businesses[$x]->categories, 0);
It returns an array with the column 0. So the response will be:
print_r($newArray);
//Array ( [0] => Chinese [1] => Vietnamese )
Then you can join it safely:
$newString = implode(",", $newArray)
echo $newString; // "Chinese, Vietnamese"

implode(', ', array_map(function($item) {
return $item[0];
}, $response->businesses[$x]->categories));

Related

How to extract certain words from a php string?

I have a long string like this I1:1;I2:2;I8:2;NA1:5;IA1:[1,2,3,4,5];S1:asadada;SA1:[1,2,3,4,5];SA1:[1,2,3,4,5];. Now I just want to get certain words like 'I1','I2','I8','NA1' and so on i.e. words between ':'&';' only ,and store them in array. How to do that efficiently?
I have already tried using preg_split() and it works but giving me wrong output. As shown below.
// $a is the string I want to extract words from
$str = preg_split("/[;:]/", $a);
print_r($str);
The output I am getting is this
Array
(
[0] => I8
[1] => 2
[2] => I1
[3] => 1
[4] => I2
[5] => 2
[6] => I3
[7] => 2
[8] => I4
[9] => 4
[10] =>
)
Array
(
[0] => NA1
[1] => 5
[2] =>
)
Array
(
[0] => IA1
[1] => [1,2,3,4,5]
[2] =>
)
Array
(
[0] => S1
[1] => asadada
[2] =>
)
Array
(
[0] => SA1
[1] => [1,2,3,4,5]
[2] =>
)
But I am expecting 'I8','I1','I2','I3','I4' also in seperated array with position [0]. Any help on how to do this.
You could try something like.
<?php
$str = 'I1:1;I2:2;I8:2;NA1:5;IA1:[1,2,3,4,5];S1:asadada;SA1:[1,2,3,4,5];SA1:[1,2,3,4,5];';
preg_match_all('/(?:^|[;:])(\w+)/', $str, $result);
print_r($result[1]); // Matches are here in $result[1]
You can perform a greedy match to match the items between ; and : using preg_match_all()
<?php
$str = 'I1:1;I2:2;I8:2;NA1:5;IA1:[1,2,3,4,5];S1:asadada;SA1:[1,2,3,4,5];SA1:[1,2,3,4,5];';
preg_match_all('/;(.+?)\:/',$str,$matches);
print_r($matches[1]);
Live Demo: https://3v4l.org/eBsod
One possible approach is using a combination of explode() and implode(). The result is returned as a string, but you can easily put it into an array for example.
<?php
$input = "I1:1;I2:2;I8:2;NA1:5;IA1:[1,2,3,4,5];S1:asadada;SA1:[1,2,3,4,5];SA1:[1,2,3,4,5];.";
$output = array();
$array = explode(";", $input);
foreach($array as $item) {
$output[] = explode(":", $item)[0];
}
echo implode(",", $output);
?>
Output:
I1,I2,I8,NA1,IA1,S1,SA1,SA1,.

Php - How to convert multiple key values array to | (Pipe) Separated string

I am working on one project with multiple array operations.
I have one variable called $product_attributes and it contains below array as value.
Array
(
[0] => Array
(
[0] => Applications
[1] => Steel; PVC; Std. Wall
)
[1] => Array
(
[0] => Blade Exp.
[1] => 0.29
)
[2] => Array
(
[0] => Fits Model
[1] => 153
)
)
Now i want to convert it into | (Pipe) Separated String like below:
Applications=Steel; PVC; Std. Wall|Blade Exp.=0.29|Fits Model=153
Below is what i have tried:
$tags = implode('|',$product_attributes);
echo "Output".$tags;
But it returns output as below:
OutputArray|Array|Array|Array|Array|Array
The solution using array_map and implode functions:
$result = implode("|", array_map(function ($v) {
return $v[0] . "=" .$v[1];
}, $product_attributes));
print_r($result);
The output:
Applications=Steel; PVC; Std. Wall|Blade Exp.=0.29|Fits Model=153

Array explode with condition

I'm facing a problem that I can't solve on my own, I can't find a way to do it.
I have those two strings:
'Germany, "Sightseeing, Travelling, Hotels"'
and
'Health, Medicin, Healthcare'
I need to explode() this strings on the , char, but only if the text, where this , lays in isn't surrounded by ".
So, as example this would be the desired results:
array(0 => 'Germany', 1 => '"Sightseeing, Travelling, Hotels"');
array(0 => 'Health', 1 => 'Medicin', 2 => 'Healthcare');
By now this is what I have:
explode(",", 'Germany, "Sightseeing, Travelling, Hotels"');
Which will give out
array(0 => 'Germany', 1 => '"Sightseeing', 2 => 'Travelling', 3 => 'Hotels"');
How can I get to this result?
See str_getcsv() how to parse csv (even if you are not reading a csv file, this is exactly what this string looks like):
<?php
print_r(str_getcsv('Germany, "Sightseeing, Travelling, Hotels"', ','));
print_r(str_getcsv('Health, Medicin, Healthcare'));
print_r(str_getcsv('D"uh!, \"Test\"', ','));
?>
results in:
Array ( [0] => Germany [1] => Sightseeing, Travelling, Hotels )
Array ( [0] => Health [1] => Medicin [2] => Healthcare )
Array ( [0] => D"uh! [1] => "Test" )
Remarks: This Function is available beginning with php version 5.3.0 and can also be configured as to what your input looks like. I added some special cases, this is a classic problem that looks far simpler than it is.
You can use php function str_getcsv.
Here an example:
$string_1 = 'Germany, "Sightseeing, Travelling, Hotels"';
$string_2 = 'Health, Medicin, Healthcare';
$result_1 = str_getcsv($string_1,',','"');
$result_2 = str_getcsv($string_2,',','"');
print_R($result_1);
print_R($result_2);
that outputs:
Array
(
[0] => Germany
[1] => Sightseeing, Travelling, Hotels
)
Array
(
[0] => Health
[1] => Medicin
[2] => Healthcare
)
You can after map each element of the resultant array, and if there is a comma you can surround it with "
foreach($result_1 as $i => $item) {
if(substr_count($item,',') > 0) {
$result_1[$i] = '"'.$item.'"';
}
}
Wich produce:
Array
(
[0] => Germany
[1] => "Sightseeing, Travelling, Hotels"
)

Grab param from string and convert to array php

I have input string from users. this input from users are unpredictable. it's mean user can input any string as they like.
I would like to filter the input that match following pattern and return it as an array
These following string pattern should works:
product=bag, product=tshirt, product=shoes
product=bag status=sold, product=jeans, product=shoes
product=all
I would like the output as array like below :
Array(
[0] => Array
(
[product] => bag
[status] => sold
)
[1] => Array
(
[product] => jeans
)
[2] => Array
(
[product] => shoes
)
)
I guess it can be achieved by use preg_match_all() beside explode. Anyone can give me example using preg_match_all ? or any other ways are ok for me as long as the best method.
$string = 'product=bag status=sold, product=tshirt, product=shoes';
$m = preg_match_all('/needregexrulehere/', $string, $matches);
You don't need a regular expression for this, you can do something like this:
$return = array();
foreach( str_getcsv( $string) as $line) {
parse_str( str_replace( ' ' , '&', $line), $temp);
$return[] = $temp;
}
This will output:
Array
(
[0] => Array
(
[product] => bag
[status] => sold
)
[1] => Array
(
[product] => tshirt
)
[2] => Array
(
[product] => shoes
)
)
I will leave error checking / input sanitation up to the OP.

Getting an array from object using SimpleXMLElement

I'm having some problems getting the array in these objects. When I print_r(), the following code is printed. $message_object is the name of the object.
SimpleXMLElement Object
(
[header] => SimpleXMLElement Object
(
[responsetime] => 2012-12-22T14:10:09+00:00
)
[data] => SimpleXMLElement Object
(
[id] => Array
(
[0] => 65233
[1] => 65234
)
[account] => Array
(
[0] => 20992
[1] => 20992
)
[shortcode] => Array
(
[0] => 3255
[1] => 3255
)
[received] => Array
(
[0] => 2012-12-22T11:04:30+00:00
[1] => 2012-12-22T11:31:08+00:00
)
[from] => Array
(
[0] => 6121843347
[1] => 6121820166
)
[cnt] => Array
(
[0] => 24
[1] => 25
)
[message] => Array
(
[0] => Go tramping wellington 11-30
[1] => Go drinking Matakana 2pm
)
)
)
I'm trying to get the id arrays out of the objects with a foreach:
foreach($message_object->data->id AS $id) {
print_r($id);
}
The following reply is sent:
SimpleXMLElement Object ( [0] => 65233 ) SimpleXMLElement Object ( [0] => 65234 )
How do I get the value of [0] or am I going about this wrong? and is there a way to loop though the results and get the object keys?
I have tried to echo $id[0] but it returns no result.
When you use print_r on a SimpleXMLElement there comes magic in between. So what you see is not actually what is there. It's informative, but just not the same as with normal objects or arrays.
To answer your question how to iterate:
foreach ($message_object->data->id as $id)
{
echo $id, "\n";
}
to answer how to convert those into an array:
$ids = iterator_to_array($message_object->data->id, 0);
As this would still give you the SimpleXMLElements but you might want to have the values you can either cast each of these elements to string on use, e.g.:
echo (string) $ids[1]; # output second id 65234
or convert the whole array into strings:
$ids = array_map('strval', iterator_to_array($message_object->data->id, 0));
or alternatively into integers:
$ids = array_map('intval', iterator_to_array($message_object->data->id, 0));
You can cast the SimpleXMLElement object like so:
foreach ($message_object->data->id AS $id) {
echo (string)$id, PHP_EOL;
echo (int)$id, PHP_EOL; // should work too
// hakre told me that this will work too ;-)
echo $id, PHP_EOL;
}
Or cast the whole thing:
$ids = array_map('intval', $message_object->data->id);
print_r($ids);
Update
Okay, the array_map code just above doesn't really work because it's not strictly an array, you should apply iterator_to_array($message_object->data_id, false) first:
$ids = array_map('intval', iterator_to_array$message_object->data->id, false));
See also: #hakre's answer.
You just need to update your foreach like this:
foreach($message_object->data->id as $key => $value) {
print_r($value);
}

Categories