remove dashes from each value in an array, then rebuild array - php

Im having a lot of trouble with this, and I'm now sure why.
I have a dynamic array, that can consist of 1 or more values:
[array] => Array
(
[0] => blurb
[1] => news
[2] => entertainment
[3] => sci
[4] => diablo-3
)
Here is my model
public function create_session_filter($filters)
{
$array = split("\|", $filters);
$filter['filter'] = $array;
$this->session->unset_userdata('filter');
$this->session->set_userdata($filter);
}
When the array $filters is run, i need to remove any dashes from any of the individual array values and replace them with spaces.
This is producing some funky results:
public function create_session_filter($filters)
{
$filterarray = array();
$array = split("\|", $filters);
foreach ($array as $filter)
{
print_r($filter);
$filterspace = implode(' ', explode('-', $filter));
$filterarray = array_push($filterarray, $filterspace);
}
$filter['filter'] = $filterarray;
$this->session->unset_userdata('filter');
$this->session->set_userdata($filter);
}
What is the correct way to do this?
Thanks

All of the exploding and imploding isn't really necessary. Nor would you need to create a new array. You can cycle through your values by reference, and modify them in a one-liner:
$array = array( "blurb", "news", "diblo-3" );
$array = str_replace( "-", " ", $array );
Which outputs:
Array
(
[0] => blurb
[1] => news
[2] => diblo 3
)
Demo: http://codepad.org/up0VoZ21

Related

array_diff() removing partial values

I am developing a hashtag search system on Instagram. And I get a list of users with their posts in the following form:
username1-idposts123455665435, username2-idposts45634563456, username3-idposts276544234....
I set up an array to be able to work with the display on my page, with the code, where $getRelatorio are the users above.
$base_array_split = preg_split("/,\s/", $getRelatorio);
$base_array_filtro = array_filter($base_array_split);
foreach($base_array_filtro as $explode_usuarios_array)
{
$explode_usuarios = explode("-", $explode_usuarios_array);
$array1[] = array(
$explode_usuarios[0], //get username
$explode_usuarios[1] // ger post id
);
}
Everything works fine. But I want to implement a Black List system, to block the display of users that the customer does not want to see.
I store it in the database in the same way, separated by a comm and to work, I also assemble an array.
$base_array_lista = preg_split("/,\s/", $listanegra);
$base_array_filtro_lista = array_filter($base_array_lista);
foreach($base_array_filtro_lista as $explode_lista_negra)
{
$is_array[] = array(
$explode_lista_negra //get username
);
}
$array2 = isset($is_array) && is_array($is_array) ? $is_array : []; //if empty
Now, I am using the following to exclude the users that the customer has blacklisted:
$arrayfinal = array();
foreach($array1 as $arr)
{
$arrayfinal[] = array_diff($arr, array_column($array2, 0));
}
$array = array_filter($arrayfinal);
The difference between the two arrays is that one has the post id.
The result:
I am able to remove the username, but the post ID is still displayed in the array.
If i remove array_column($array2, 0) it doesn't work.
If i use array_diff_assoc it doesn't work either
var_dump:
[0] => Array
(
[0] => username1
[1] => 2577195852001190087
)
[1] => Array
(
[0] => username2
[1] => 2577195809822230254
)
[2] => Array
(
[0] => 2577195306530472731 //username removed, bud post id is not - need to remove that too
)
var_dump expected:
[0] => Array
(
[0] => username1
[1] => 2577195852001190087
)
[1] => Array
(
[0] => username2
[1] => 2577195809822230254
)
You can index on username or postid and do it like this (indexed on postid):
foreach(explode(', ', $string) as $values) {
$parts = explode('-idposts', $values);
$result[$parts[1]] = $parts[0];
}
$blacklist = ['username3'];
$result = array_diff($result, $blacklist);
Or using the format you have:
foreach(explode(', ', $string) as $values) {
$parts = explode('-idposts', $values);
$result[$parts[0]] = $parts;
}
$blacklist = ['username3'];
$result = array_diff_key($result, array_flip($blacklist));
Here's another way.. flatten the arrays using json_encode, comparing then reinflating.
View a demo here:
https://www.tehplayground.com/IcpKbUyFltbXhNQp
<?php
$array1 = array(
array("username1", "2577195852001190087"),
array("username2", "1577195852001190087"),
array("username3", "3577195852001190087")
);
$array2 = array(
array("username2", "1577195852001190087"),
array("username3", "3577195852001190087")
);
$a=array_map(function($v) { return json_encode($v); }, $array1);
$b=array_map(function($v) { return json_encode($v); }, $array2);
$arrayfinal = array_map(function($v) { return json_decode($v); }, array_diff($a, $b) );
$array = array_filter($arrayfinal);
print_r($array);

Remove duplicates from a multi-dimensional array based on 2 values

I have an array that looks like this
$array = array(
array("John","Smith","1"),
array("Bob","Barker","2"),
array("Will","Smith","2"),
array("Will","Smith","4")
);
In the end I want the array to look like this
$array = array(
array("John","Smith","1"),
array("Bob","Barker","2"),
array("Will","Smith","2")
);
The array_unique with the SORT_REGULAR flag checks for all three value. I've seen some solutions on how to remove duplicates based on one value, but I need to compare the first two values for uniqueness.
Simple solution using foreach loop and array_values function:
$arr = array(
array("John","Smith","1"), array("Bob","Barker","2"),
array("Will","Smith","2"), array("Will","Smith","4")
);
$result = [];
foreach ($arr as $v) {
$k = $v[0] . $v[1]; // considering first 2 values as a unique key
if (!isset($result[$k])) $result[$k] = $v;
}
$result = array_values($result);
print_r($result);
The output:
Array
(
[0] => Array
(
[0] => John
[1] => Smith
[2] => 1
)
[1] => Array
(
[0] => Bob
[1] => Barker
[2] => 2
)
[2] => Array
(
[0] => Will
[1] => Smith
[2] => 2
)
)
Sample code with comments:
// array to store already existing values
$existsing = array();
// new array
$filtered = array();
foreach ($array as $item) {
// Unique key
$key = $item[0] . ' ' . $item[1];
// if key doesn't exists - add it and add item to $filtered
if (!isset($existsing[$key])) {
$existsing[$key] = 1;
$filtered[] = $item;
}
}
For fun. This will keep the last occurrence and eliminate the others:
$array = array_combine(array_map(function($v) { return $v[0].$v[1]; }, $array), $array);
Map the array and build a key from the first to entries of the sub array
Use the returned array as keys in the new array and original as the values
If you want to keep the first occurrence then just reverse the array before and after:
$array = array_reverse($array);
$array = array_reverse(array_combine(array_map(function($v) { return $v[0].$v[1]; },
$array), $array));

PHP Puttin values of array into multidimensional array

Hello I want to put values of single array into a multidimensional array with each value on a n+1
This is my array $structures
Array
(
[0] => S
[1] => S.1
[2] => S-VLA-S
[3] => SB
[4] => SB50
)
What I want for output is this
Array
(
[S] => Array(
[S.1] => Array (
[S-VLA-S] => Array (
[SB] => Array (
[SB50] => Array(
'more_attributes' => true
)
)
)
)
)
)
This is what I have tried so far
$structures = explode("\\", $row['structuurCode']);
foreach($structures as $index => $structure) {
$result[$structure][$structure[$index+1]] = $row['structuurCode'];
}
The values of the array is a tree structure that's why it would be handy to have them in an multidimensional array
Thanks in advance.
It becomes pretty trivial once you start turning it inside out and "wrap" the inner array into successive outer arrays:
$result = array_reduce(array_reverse($structures), function ($result, $key) {
return [$key => $result];
}, ['more_attributes' => true]);
Obviously a more complex solution would be needed if you needed to set multiple paths on the same result array, but this is the simplest solution for a single path.
Slightly different approach:
$var = array('a','an','asd','asdf');
$var2 = array_reverse($var);
$result = array('more_attributes' => true);
$temp = array();
foreach ($var2 as $val) {
$temp[$val] = $result;
$result = $temp;
$temp = array();
}

PHP combine several arrays to one

I want to combine several arrays into one, they are the result of a form post with an unknown number of elements, eg:
$ids = [53,54,55];
$names = ['fire','water','earth'];
$temps = [500,10,5];
What i want is to make a function that takes these arrays as an input and produces a single output, like
$elements = [['id'=>53,'name'=>'fire','temp'=>500] , ['id'=>54,'name'=>'water','temp'=>500] , ['id'=>55,'name'=>'earth','temp'=>500]]
I came up with the following solution:
function atg($array) {
$result = array();
for ($i=0;$i<count(reset($array));$i++) {
$newAr = array();
foreach($array as $index => $val) {
$newAr[$index] = $array[$index][$i];
}
$result[]=$newAr;
}
return $result;
}
It can be called like
$elements = atg(['id' => $ids, 'name' => $names, 'temp' => $temps]);
And it produces the right output. To me it seems a bit overly complicated though, and I'm sure this is a common problem in PHP for form posts, combining seperate fields into a single array per item. What would be a better solution?
You can loop through all of your 3 arrays at once with array_map(). There you can just return the new array with a value of each of the 3 arrays, e.g.
$result = array_map(function($id, $name, $temp){
return ["id" => $id, "name" => $name, "temp" => $temp];
}, $ids, $names, $temps);
Use below code:-
$ids = [53,54,55];
$names = ['fire','water','earth'];
$temps = [500,10,5];
$result = [];
foreach($ids as $k=>$id){
$result[$k]['id'] = $id;
$result[$k]['name'] =$names[$k];
$result[$k]['temp'] = $temps[0];
}
echo '<pre>'; print_r($result);
output:-
Array
(
[0] => Array
(
[id] => 53
[name] => fire
[temp] => 500
)
[1] => Array
(
[id] => 54
[name] => water
[temp] => 500
)
[2] => Array
(
[id] => 55
[name] => earth
[temp] => 500
)
)
If you are ok with a destructive solution, array_shift could do the trick :
$elements = array();
while (!empty($ids)) {
$elements[] = array(
'id' => array_shift($ids),
'name' => array_shift($names),
'temp' => array_shift($temps),
);
}
If you want to make a function, using the same arguments than your example, a solution could be
function atg($array) {
$elements = array();
while (!empty($array[0])) {
$new_element = array();
foreach ($array as $key_name => $array_to_shift) {
$new_element[$key_name] = array_shit($array_to_shift);
}
$elements[] = $new_element;
}
return $elements;
}
$result[$ids]['name'] = $names[0];
$result[$ids]['temp'] = $temps[0]

weird php array

my php array looks like this:
Array (
[0] => dummy
[1] => stdClass Object (
[aid] => 1
[atitle] => Ameya R. Kadam )
[2] => stdClass Object (
[aid] => 2
[atitle] => Amritpal Singh )
[3] => stdClass Object (
[aid] => 3
[atitle] => Anwar Syed )
[4] => stdClass Object (
[aid] => 4
[atitle] => Aratrika )
) )
now i want to echo the values inside [atitle].
to be specific i want to implode values of atitle into another variable.
how can i make it happen?
With PHP 5.3:
$result = array_map(function($element) { return $element->atitle; }, $array);
if you don't have 5.3 you have to make the anonymous function a regular one and provide the name as string.
Above I missed the part about the empty element, using this approach this could be solved using array_filter:
$array = array_filter($array, function($element) { return is_object($element); });
$result = array_map(function($element) { return $element->atitle; }, $array);
If you are crazy you could write this in one line ...
Your array is declared a bit like this :
(Well, you're probably, in your real case, getting your data from a database or something like that -- but this should be ok, here, to test)
$arr = array(
'dummy',
(object)array('aid' => 1, 'atitle' => 'Ameya R. Kadam'),
(object)array('aid' => 2, 'atitle' => 'Amritpal Singh'),
(object)array('aid' => 3, 'atitle' => 'Anwar Syed'),
(object)array('aid' => 4, 'atitle' => 'Aratrika'),
);
Which means you can extract all the titles to an array, looping over your initial array (excluding the first element, and using the atitle property of each object) :
$titles = array();
$num = count($arr);
for ($i=1 ; $i<$num ; $i++) {
$titles[] = $arr[$i]->atitle;
}
var_dump($titles);
This will get you an array like this one :
array
0 => string 'Ameya R. Kadam' (length=14)
1 => string 'Amritpal Singh' (length=14)
2 => string 'Anwar Syed' (length=10)
3 => string 'Aratrika' (length=8)
And you can now implode all this to a string :
echo implode(', ', $titles);
And you'll get :
Ameya R. Kadam, Amritpal Singh, Anwar Syed, Aratrika
foreach($array as $item){
if(is_object($item) && isset($item->atitle)){
echo $item->atitle;
}
}
to get them into an Array you'd just need to do:
$resultArray = array();
foreach($array as $item){
if(is_object($item) && isset($item->atitle)){
$resultArray[] = $item->atitle;
}
}
Then resultArray is an array of all the atitles
Then you can output as you'd wish
$output = implode(', ', $resultArray);
What you have there is an object.
You can access [atitle] via
$array[1]->atitle;
If you want to check for the existence of title before output, you could use:
// generates the title string from all found titles
$str = '';
foreach ($array AS $k => $v) {
if (isset($v->title)) {
$str .= $v->title;
}
}
echo $str;
If you wanted these in an array it's just a quick switch of storage methods:
// generates the title string from all found titles
$arr = array();
foreach ($array AS $k => $v) {
if (isset($v->title)) {
$arr[] = $v->title;
}
}
echo implode(', ', $arr);
stdClass requires you to use the pointer notation -> for referencing whereas arrays require you to reference them by index, i.e. [4]. You can reference these like:
$array[0]
$array[1]->aid
$array[1]->atitle
$array[2]->aid
$array[2]->atitle
// etc, etc.
$yourArray = array(); //array from above
$atitleArray = array();
foreach($yourArray as $obj){
if(is_object($obj)){
$atitleArray[] = $obj->aTitle;
}
}
seeing as how not every element of your array is an object, you'll need to check for that.

Categories