Rewrite 2d array, which contains only some keys - php

I am using Animate.css for Bootstrap carousel and I need to sort the animations.
I have made an array called $anims, which contains all the animations. I want to make a new variable which contains only entrance animations, for example. So this is my array.
$anims = array(
"Bouncing Entrances" => array(
"bounceIn",
"bounceInDown",
....
),
"Bouncing Exits" => array(
"bounceOut",
"bounceOutDown",
....
),
"Fading Entrances" => array(
"fadeIn",
"fadeInDown",
....
),
......
)
$enrtyAnims = ...
?>
After processing it should look like that:
$anims = array(
"Bouncing Entrances" => array(
"bounceIn",
"bounceInDown",
....
),
"Fading Entrances" => array(
"fadeIn",
....
)
)
But I don't have any idea how to do it with the keys. I want to be able to say I want new array with keys X and Y and it makes it.

You can simply use array_filter function with third flag parameter along with the flag ARRAY_FILTER_USE_KEY so your code looks like as
$result_array = array_filter($anims,function($k){
return (strpos($k,"Entrances") !== false);
},ARRAY_FILTER_USE_KEY);
Note: Flags as third parameter are introduced in PHP versions >= 5.6.0
Demo

Access the desired elements by key and create a new array using these items, like this:
$anims = array(
'Bouncing Entrances' => $anims['Bouncing Entrances'],
'Fading Entrances' => $anims['Fading Entrances'],
// ...
);
EDIT: forgot to preserve the keys.
If there's a certain pattern by which you want to filter the animations, you can use array_filter() function, like #Uchiha said.

Related

Searching through arrays and Creating a custom array in PHP

I having an issue merging arrays. I have 3 arrays that show particular data. I need a way to search through all three arrays and if the record matches the date I need to store it in a new custom array.
I have 3 arrays that need to merge them using the date
The arrays are as follows.
// ARRAY 1
$transactions = array(
array(
"date"=>"2021-03-01",
"trans_count"=>100,
"trans_amount"=>5300
),
array(
"date"=>"2021-03-02",
"trans_count"=>95,
"trans_amount"=>5035
),
array(
"date"=>"2021-03-03",
"trans_count"=>105,
"trans_amount"=>5565
)
);
// ARRAY 2
$overdrafts = array(
array(
"date"=>"2021-03-01",
"od_amount"=>500
),
array(
"date"=>"2021-03-02",
"od_amount"=>1000
),
);
// ARRAY 3
$payouts= array(
array(
"date"=>"2021-03-02",
"amount"=>2300
)
);
I tried to write a function but I got stuck. The end goal is to collect all records from all 3 arrays and coming up with one array.
the expected result should look like this.
$merged_arr = array(
array(
"date"=>"2021-03-01",
"type"=>"transactions",
"trans_count"=>100,
"trans_amount"=>5300
),
array(
"date"=>"2021-03-01",
"type"=>"overdrafts",
"od_amount"=>500,
),
array(
"date"=>"2021-03-02",
"type"=>"transactions",
"trans_count"=>95,
"trans_amount"=>5035
),
array(
"date"=>"2021-03-02",
"type"=>"overdrafts",
"od_amount"=>1000
),
array(
"date"=>"2021-03-02",
"type"=>"payout",
"od_amount"=>2300
),
);
Not 100% sure of how to add the type for each of the different types automatically in a nice way, I'd suggest just adding the types directly on the initial arrays, or looping through each before merging them together.
As for the merging and sorting it's pretty easy and can be done with built-in functionality.
$merged_arr = array_merge($transactions, $overdrafts, $payouts);
usort($merged_arr, function ($left, $right) {
return new DateTime($left['date']) <=> new DateTime($right['date']);
});
// Demo merged array.
print "<pre>";
var_export($merged_arr);
The sort function will work with PHP 7 and up.

PHP: How do I echo the results of this array?

$header_content = array();
$header_content['pageone'][] = array(
'image' => 'photo-one.png',
'desc' => "One. Some text here.",
);
$header_content['pagetwo'][] = array(
'image' => 'photo-two.png',
'desc' => "Two. Some text here.",
);
I do not want to echo the entire array, just certain parts when called... like $header_content['pageone']['image'], except this doesn't work... How do you go about echoing parts of an array?
I have searched but it's all a little confusing right now for me. Thanks.
Define it like -
$header_content['pagetwo'] = array(
'image' => 'photo-two.png',
'desc' => "Two. Some text here.",
);
The keys are different pageone, pagetwo. No need of that extra index i think. And then access it - echo $header_dontent['pagetwo']['image'];
For printing array values, you can use :
print_r function
Example : print_r($array)
Specific key data can be accessed through : print_r($array[$key])
OR
var_dump function
Example : var_dump($array)
Specific key data can be accessed through : var_dump($array[$key])
use it like $header_content['pageone'][0]['image']
Since
$header_content['pageone'][] = array();
[] appends an element at the end of an array.

Computing difference by comparing nested arrays

I was under the impression that array_diff evaluates the difference between the values in the two arrays. But somehow it doesn't work...I am guessing nested arrays is the problem here. Clearly array_diff_assoc is not the solution as keys are irrelevant in this case.
I don't even want to make it go nested, just see whether the value (in this case, array) inside are identical or not.
$file_details = array(
array(
"uuid" => "45ebdbaa-380b-483b-80a2-73d7c53088e2",
"filename" => "train_failure.mp3",
),
array("uuid" => "97baa061-4208-4aeb-8136-eb76c0932a3d",
"filename" => "train_work1.mp3"
),
array("uuid" => "ksjdfls6-eb76c0932a3d",
"filename" => "train.mp3"
),
);
$items = array(
array(
"uuid" => "45ebdbaa-380b-483b-80a2-73d7c53088e2",
"filename" => "train_failure.mp3",
),
array(
"uuid" => "1233489eb76c0932a3d",
"filename" => "train.mp3"
),
);
print_r(array_diff($file_details,$items));
This returns an empty array...How should I go about fixing this?
My desired output is
array(
"uuid" => "97baa061-4208-4aeb-8136-eb76c0932a3d",
"filename" => "train_work1.mp3"
),
array(
"uuid" => "ksjdfls6-eb76c0932a3d",
"filename" => "train.mp3"
),
UPDATE -: *I know array_diff doesn't work for 1-d array, I'm just surprised there is no direct php function for doing a comparison on multidimensional arrays.*
Your array items are arrays and cannot be compared as strings (array_diff() will treat all values as strings - for example, it will try to stringify objects via calling their __toString() method).
You can use array_udiff() instead:
$rgResult=array_udiff($file_details, $items, function($rgX, $rgY)
{
return $rgX['uuid']<$rgY['uuid']?-1:$rgX['uuid']!=$rgY['uuid'];
});
array_diff() method is supposed to work with 1-d array.
From the array_diff() man page:
Note:
This function only checks one dimension of a n-dimensional array. Of
course you can check deeper dimensions by using
array_diff($array1[0], $array2[0]);

sort php array by x then y

I want to sort an array by 'hits', but I also want to look for a particular ID and set that as the first iteration, then continue the 'hits' sort.
For example, I have a multidimensional array:
$myarray = array(
array(
"id"=>10,
"hits"=>80
),
array(
"id"=>14,
"hits"=>50
),
array(
"id"=>15,
"hits"=>700
),
array(
"id"=>18,
"hits"=>200
)
);
I want to test whether the id is something particular, i.e. if the id==18 then put it first, then sort by hits. How would I do this, using usort and a custom function?
I think I'm looking for something similar to:
function customsort($a,$b){
if($a["id"]==18){ //or b==18?
return -1;
} else {
return $a["hits"]>$b["hits"];
}
}
usort($myarray,"customsort");
The outcome I would like is for the order to be :
array(
"id"=>18,
"hits"=>200
),
array(
"id"=>14,
"hits"=>50
),
array(
"id"=>10,
"hits"=>80
),
array(
"id"=>15,
"hits"=>700
)
(or if they were labelled ABCD then I need it to be DBAC)
The only thing in your code that might make this NOT work is the return $a["hits"]>$b["hits"];. Your function should return 1/-1 only (not true/false), so change that line to: return $a["hits"]>$b["hits"]?1:-1; and it should work as expected.
Sure enough, it works: http://codepad.org/ItyIa7fB

Replace array key integers with string

$string = "php, photoshop, css";
I'm producing an array from the comma separated values above using the str_getcsv() function:
$array = str_getcsv($string);
Result:
Array ( [0] => php [1] => photoshop [2] => css )
How can I replace the key integers with a string tag for all elements like seen below?
Array ( [tag] => php [tag] => photoshop [tag] => css )
Edit: if not possible what alternative can I apply? I need the array keys to be identical for a dynamic query with multiple OR clauses
e.g.
SELECT * FROM ('posts') WHERE 'tag' LIKE '%php% OR 'tag' LIKE '%photoshop% OR 'tag' LIKE '%css%'
I'm producing the query via a function that uses the array key as a column name and value as criteria.
That is not possible. You can have only one item per key. But in your example, the string "tag" would be the key of every item.
The other way arround would work. So having an array like this:
array('php' => 'tag', 'photoshop' => 'tag', 'css' => 'tag');
This might help you, if you want to save the "type" of each entry in an array. But as all the entries of your array seems to be from the same type, just forget about the "tag" and only store the values in a numeric array.
Or you can use a multidimensional array within the numeric array to save the type:
array(
0 => array( 'type' => 'tag', 'value' => 'php' ),
1 => array( 'type' => 'tag', 'value' => 'photoshop' ),
2 => array( 'type' => 'tag', 'value' => 'css' )
);
But still using just an numeric array should be fine if all the entries have the same type. I can even think of a last one:
array(
'tag' => array('php', 'photoshop', 'css')
);
But even if I repeat myself: Just use an ordinary array and name it something like $tag!
BTW: explode(', ', %string) is the more common function to split a string.
To build SQL statement you might do something like this:
// ... inside you build function
if(is_array($value)){
$sql .= "'".$key."' LIKE '%."implode("%' OR '".$key."' LIKE '%", $value)."%'";
} else {
$sql .= "'".$key."' LIKE '%".$value."%'";
}
This might look confusing but it's much cleaner than runnig into two foreach-loops building the query.
That won't work. Your array keys have to be unique, or subsequent additions will simply overwrite the previous key.
As the others said, keys have to be unique. Otherwise, which element should be returned if you access $arr['tag']? If you now say "all of them", then create a nested array:
$array = array();
$array['tag'] = str_getcsv($string);
The value $array['tag'] will be another array (the one you already have) with numerical keys. This makes, because you have a list of tags and lists can be represented as arrays too.
Understanding arrays is very important if you want to work with PHP, so I suggest to read the array manual.
Assuming you know the size of your array beforehand
$tags = array("tag1","tag2","tag3");
$data = array("php","photoshop","css");
$myarray = array();
for ($i=0; $i<count($data); $i++) {
$myarray[$i] = array($data[$i], $tags[$i]);
}
Then
echo $myarray[0][0] . ", " . $myarray[0][1];
Outputs:
php, tag1

Categories