How to create an array from string seperated values? - php

I have an array like:
Array
(
[0] => Mechanical Engineering,CEO
)
Now I want to convert it in this form:
Array
(
[0] => Mechanical Engineering
[1] => CEO
)

You can use like below.
$str = 'Mechanical Engineering,CEO';
$arrayStr = explode(',',$str );
print_r($arrayStr);

Note: Assuming your input array has only one key "Mechanical Engineering,CEO".
We need current() function to access the array element.
Since you want to split your data every time there's a comma, we need explode()
function.
$input = array("Mechanical Engineering,CEO");
$output = explode(",", current($input));

Related

pull dynamic element in single array

I am trying to pull dynamic element in single array but result is not showing properly
Ex:
$array =array();
$element="'abc1','abc2'";
$array=array('abc',$element);
//I want result like that:
array[
[0]=>abc,
[1]=>abc1,
[2]=>ab
]
If you need to parse a string of elements to an array you can use one of the csv functions. You may then merge your arrays.
$array = array('abc');
$string_elements = "'abc1','abc2'";
$array_elements = str_getcsv($string_elements, ',', "'");
$array = array_merge($array, $array_elements);
var_export($array);
Output:
array (
0 => 'abc',
1 => 'abc1',
2 => 'abc2',
)
Alternatively to add each array element to the end of another array you can push them like so using a splat:
array_push($array, ...$array_elements);
According to my understanding, $element is storing string not an array so even if you try to get output it will display in following format
Array
(
[0] => abc
[1] => 'abc1','abc2'
)
Instead of this you can store array in $element variable and use array_merge() function to get required output e.g.
$element = array('abc1','abc2');
$array = array('abc');
$result = array_merge($array,$element);
// Output
Array
(
[0] => abc
[1] => abc1
[2] => abc2
)

PHP from string to multiple arrays at the hand of placeholders

Good day,
I have an I think rather odd question and I also do not really know how to ask this question.
I want to create a string variable that looks like this:
[car]Ford[/car]
[car]Dodge[/car]
[car]Chevrolet[/car]
[car]Corvette[/car]
[motorcycle]Yamaha[/motorcycle]
[motorcycle]Ducati[/motorcycle]
[motorcycle]Gilera[/motorcycle]
[motorcycle]Kawasaki[/motorcycle]
This should be processed and look like:
$variable = array(
'car' => array(
'Ford',
'Dodge',
'Chevrolet',
'Corvette'
),
'motorcycle' => array(
'Yamaha',
'Ducati',
'Gilera',
'Kawasaki'
)
);
Does anyone know how to do this?
And what is it called what I am trying to do?
I want to explode the string into the two arrays. If it is a sub array
or two individual arrays. I do not care. I can always combine the
latter if I wish so.
But from the above mentioned string to two arrays. That is what I
want.
Solution by Dlporter98
<?php
///######## GET THE STRING FILE OR DIRECT INPUT
// $str = file_get_contents('file.txt');
$str = '[car]Ford[/car]
[car]Dodge[/car]
[car]Chevrolet[/car]
[car]Corvette[/car]
[motorcycle]Yamaha[/motorcycle]
[motorcycle]Ducati[/motorcycle]
[motorcycle]Gilera[/motorcycle]
[motorcycle]Kawasaki[/motorcycle]';
$str = explode(PHP_EOL, $str);
$finalArray = [];
foreach($str as $item){
//Use preg_match to capture the pieces of the string we want using a regular expression.
//The first capture will grab the text of the tag itself.
//The second capture will grab the text between the opening and closing tag.
//The resulting captures are placed into the matches array.
preg_match("/\[(.*?)\](.*?)\[/", $item, $matches);
//Build the final array structure.
$finalArray[$matches[1]][] = $matches[2];
}
print_r($finalArray);
?>
This gives me the following array:
Array
(
[car] => Array
(
[0] => Ford
[1] => Dodge
[2] => Chevrolet
[3] => Corvette
)
[motorcycle] => Array
(
[0] => Yamaha
[1] => Ducati
[2] => Gilera
[3] => Kawasaki
)
)
The small change I had to make was:
Change
$finalArray[$matches[1]] = $matches[2]
To:
$finalArray[$matches[1]][] = $matches[2];
Thanks a million!!
There are many ways to convert the information in this string to an associative array.
split the string on the new line into an array using the explode function:
$str = "[car]Ford[/car]
[car]Dodge[/car]
[car]Chevrolet[/car]
[car]Corvette[/car]
[motorcycle]Yamaha[/motorcycle]
[motorcycle]Ducati[/motorcycle]
[motorcycle]Gilera[/motorcycle]
[motorcycle]Kawasaki[/motorcycle]";
$items = explode(PHP_EOL, $str);
At this point each delimited item is now an array entry.
Array
(
[0] => [car]Ford[/car]
[1] => [car]Dodge[/car]
[2] => [car]Chevrolet[/car]
[3] => [car]Corvette[/car]
[4] => [motorcycle]Yamaha[/motorcycle]
[5] => [motorcycle]Ducati[/motorcycle]
[6] => [motorcycle]Gilera[/motorcycle]
[7] => [motorcycle]Kawasaki[/motorcycle]
)
Next, loop over the array and pull out the appropriate pieces needed to build the final associative array using the preg_match function with a regular expression:
$finalArray = [];
foreach($items as $item)
{
//Use preg_match to capture the pieces of the string we want using a regular expression.
//The first capture will grab the text of the tag itself.
//The second capture will grab the text between the opening and closing tag.
//The resulting captures are placed into the matches array.
preg_match("/\[(.*?)\](.*?)\[/", $item, $matches);
//Build the final array structure.
$finalArray[$matches[1]] = $matches[2]
}
The following is an example of what will be found in the matches array for a given iteration of the foreach loop.
Array
(
[0] => [motorcycle]Gilera[
[1] => motorcycle
[2] => Gilera
)
Please note that I use the PHP_EOL constant to explode the initial string. This may not work if the string was pulled from a different operating system than the one you are running this code on. You may need to replace this with the actual end of line characters that is being used by the string.
Why don't you create two separate arrays?
$cars = array("Ford", "Dodge", "Chevrolet", "Corvette");
$motorcycle = array("Yamaha", "Ducati", "Gilera", "Kawasaki");
You could also use an Associative array to do this.
$variable = array("Ford"=>"car", "Yamaha"=>"motorbike");

Splitting a String after every nth element php

I have a string in this form
$navigation="<li>A</li><li>B</li><li>C</li><li>A</li><li>B</li><li>C</li><li>A</li><li>B</li><li>C</li>";
The list is generated dynamically from database and hence the number of elements is not fixed. I want to split this list after every 5th element, so if there are 10 "<li></li>" elements in this string I should get two strings output1 and output2.
I have tried explode but it doesn't work as we have to impose restriction on nth element and I have also tried string_split but that is not working also.
So what is the solution?
Ahmar
You can do it this way:
$s = "<li>A</li><li>B</li><li>C</li><li>A</li><li>B</li><li>C</li><li>A</li><li>B</li><li>C</li>";
if (preg_match_all('~((?:<li>.*?</li>){5})~i', $s, $arr))
print_r($arr);
OUTPUT:
Array
(
[0] => Array
(
[0] => <li>A</li><li>B</li><li>C</li><li>A</li><li>B</li>
)
[1] => Array
(
[0] => <li>A</li><li>B</li><li>C</li><li>A</li><li>B</li>
)
)

PHP Convert multidimensional array to match format of another

I have two arrays, one is generated by using explode() on a comma separated string and the other is generated from result_array() in Codeigniter.
The results when doing print_r are:
From explode():
Array
(
[0] => keyword
[1] => test
)
From database:
Array
(
[0] => Array
(
[name] => keyword
)
[1] => Array
(
[name] => test
)
)
I need them to match up so I can use array_diff(), what's the best way to get them to match? Is there something other than result_array() in CI to get a compatible array?
You could create a new array like this:
foreach($fromDatabase as $x)
{
$arr[] = $x['name'];
}
Now, you will have two one dim arrays and you can run array_dif.
$new_array = array();
foreach ($array1 as $line) {
$new_array[] = array('name' => $line);
}
print_r($new_array);
That should work for you.

php handle arrays

I have an array that contains entries that themselves contain two types of entries.
For simplicity sake, let's say that the entries are like this:
a|1
b|4
a|2
c|5
b|3
etc.
In fact they represent categories and subcategories in my database.
I will use explode to break these entries into letters and digits.
The question is: I want to group them by category.
What's the easiest way to create a multilevel array, which could be sorted by letters:
a|1
a|2
b|4
b|3
c|5
?
How about something like this?
$input = array('a|1','b|4','a|2','c|5','b|3');
$output = array();
foreach($input as $i){
list($key,$val) = explode("|",$i);
$output[$key][] = $val;
}
Output:
Array
(
[a] => Array
(
[0] => 1
[1] => 2
)
[b] => Array
(
[0] => 4
[1] => 3
)
[c] => Array
(
[0] => 5
)
)
<?php
$your_array = array();
$your_array[a] = array('1','2','3');
$your_array[b] = array('4','5','6');
print_r($your_array);
?>
I take it that your entries are strings (relying on the fact that you want to use explode() on them).
If so you can simply sort the array by using sort($array), and then iterate on that array and explode the values and put them in another array, which will be sorted by the previous array's order.

Categories