php array_filter send empty value - php

I have this array:
Array (
[0] => http://localhost/cms/uploads/files/1/images/hd-allpaper-40.jpg
[1] => http://localhost/cms/uploads/files/1/images/IMG_6217.JPG
[2] =>
)
Now with this code, serialize data and insert to my database :
foreach(array_filter($_POST['image_url']) as $image_url) {
if(!empty($image_url)) {
$url = parse_url(array_shift($_POST['image_url']));
preg_match('/[0-99999]\/.*/', $url['path'], $matches);
$value['gallery_data'] = serialize((array(
array_filter($matches[0]),
array_values($_POST['image_title']),
array_values($_POST['image_alt'])
)));
print_r $value['gallery_data'];
}
}
But when i print_r $value['gallery_data']; matches[0] send empty value.
EDIT : when replace $matches[0] with $_POST['image_url'] my code worked true.
var_dump(matches[0]):string(28) "1/images/hd-wallpaper-40.jpg" string(21) "1/images/IMG_6217.JPG"
how do fix this problem ?!

Related

Custom While in json array

Its My PHP Code:
$res_media=mysql_query("SELECT * FROM mv_media");
$media = array();
while($resualt_media = mysql_fetch_assoc($res_media)) {
$media[]= $resualt_media['title'];
}
echo $media;
And Its My output:
["Test","Test","Test","Test","Test"]
I want Change it to this format :
["Test"],["Test"],["Test"],["Test"],["Test"]
I changed My Code to this code :
$res_media=mysql_query("SELECT * FROM mv_media");
$media = array();
while($resualt_media = mysql_fetch_assoc($res_media)) {
$media[]= [$resualt_media['title']];
}
echo $media;
Now My OutPut :
[["Test","Test","Test","Test","Test"]]
But I need This custom output:
[["Test"],["Test"],["Test"],["Test"],["Test"],["ItsMyCustomChild"]]
I want add Custom Child with out database!
You can change $media[] = [<value>] to $media[][] = <value> and it will work, because then you'll create a new array inside an array.
I would suggest this approach:
<?php
$input = json_decode('["Test","Test","Test","Test","Test"]');
$output = [];
array_walk($input, function($element) use (&$output) {
$output[] = [$element];
});
var_dump(json_encode($output));
Alternatively this can be simplified to just:
<?php
$data = json_decode('["Test","Test","Test","Test","Test"]');
array_walk($data, function(&$element) {
$element = [$element];
});
var_dump(json_encode($data));
The created array structure obviously is:
Array
(
[0] => Array
(
[0] => Test
)
[1] => Array
(
[0] => Test
)
[2] => Array
(
[0] => Test
)
[3] => Array
(
[0] => Test
)
[4] => Array
(
[0] => Test
)
)
Which, if you again json_encode() it, results in the desired format:
string(46) "[["Test"],["Test"],["Test"],["Test"],["Test"]]"
The specific issue you are actually dealing with is not so much the creation of the desired structure, but that you are trying to modify the JSON string instead of the actual array you want to work with. That is why a call to json_decode() is used initially.
$res_media=mysql_query("SELECT * FROM mv_media");
$media = array();
while($resualt_media = mysql_fetch_assoc($res_media)) {
array_push($media,array($resualt_media['title']));
}
print_r $media;
You just need to change below line. and you will get your desired result.
$media[][]= $resualt_media['title'];
if you want to see what you get . you need to add json_encode() after the while.
like below
echo json_encode($media);

php Regular expressions basic

I want to regex thread_id in this html code by using php
<a id="change_view" class="f_right" href="pm.php?view=chat&thread_id=462075438105382912">
I wrote this code however it return empty array to me
$success = preg_match_all('/pm\.php\?view=chat&thread_id=([^"]+)/', $con, $match2);
is there any problem in my php code ?
Well, you said it is giving you an empty array. But it is not. Here is the value returned by print_r()
Array
(
[0] => Array
(
[0] => pm.php?view=chat&thread_id=462075438105382912
)
[1] => Array
(
[0] => 462075438105382912
)
)
But It is not returning what you want it to. The regular expression to get string that comes after thread_id= and before & or " is :
/(?<=thread_id=).*(?=\"|&)/
Working example :
<?php
$con = '<a id="change_view" class="f_right" href="pm.php?view=chat&thread_id=462075438105382912">link</a>';
$match2 = Array();
preg_match_all('/(?<=thread_id=).*(?=\"|&)/', $val, $arr);
echo "<pre>";
print_r($arr);
echo "</pre>";
?>
Output :
Array
(
[0] => Array
(
[0] => 462075438105382912
)
)
If you're only looking for the thread_id, this should do it.
$success = preg_match_all('/(thread_id=)([\d]+)/', $con, $match2);
if (preg_match('/thread_id=[0-9]*/', $line, $matches))
$thread_id = $matches[0];

How to not echo array if previous one's key has been echoed already

This is what I get after a print_r($myArray) (wrapped in pre) on my array.
Array
(
[0] => 203.143.197.254
[1] => not/available
)
Array
(
[0] => 40.190.125.166
[1] => articles/not/a/page
)
Array
(
[0] => 25.174.7.82
[1] => articles/not/a/page
)
How would I return or echo just the first two in this case (no regex), given the fact that I would like to only output each array whose [1] value has not been echoed before?
My list as far more entries and $myArray[1] is sometimes the same, I want to skip echoing the same thing.
I have tried array_unique but I can't get it to work as param 1 is expected to be an array.
print_r(array_unique($myArray));
This works. Didn't do a full copy paste job but hopefully you get the idea of the logic
$echoed = array();
foreach($array as $arr) {
if(!in_array($arr[1],$echoed)) {
echo $arr[1];
$echoed[] = $arr[1];
}
}
$echoedBefore = array();
print_r(array_filter($myArray, function($entry) {
global $echoedBefore;
$alreadyEchoed = in_array($entry[1], $echoedBefore);
if (!$alreadyEchoed) {
$echoedBefore[] = $entry[1];
}
return !$alreadyEchoed;
}));

Why doesn't my recursive array search work on this array of data?

I have a recursive array search function which has previously been working a treat. For some reason though now it appears to be telling me things exist in the array which actually don't.
IE, I have an array like this
Array
(
[0] => Array
(
[name] => people
[groups] => Array
(
[0] => Array
(
[name] => tom
)
[1] => Array
(
[name] => john
)
)
)
)
And my recursive search function:
function searchArrayRecursive($needle, $haystack){
foreach ($haystack as $key => $arr) {
if(is_array($arr)) {
$ret=searchArrayRecursive($needle, $arr);
if($ret!=-1) return $key.','.$ret;
} else {
if($arr == $needle) return (string)$key;
}
}
return -1;
}
If I were to do the following however:
$search = searchArrayRecursive('kim',$the_array);
if($search != -1) {
echo 'result: found<br />';
} else {
echo 'result: not found';
}
I get result: found
Its clearly not in the array. Maybe my function never worked. maybe my heads on backwards. Any ideass?
note: I also get result: found when I search for tom or john o.O
This example works as provided. Possibly your actual data has mixed case? ('john' != 'John') or possibly extra spaces or a stray newline because they weren't trimmed when the array was created?
Try a var_dump() instead of a print_r(). It should show you the exact nature of the data you are trying to search. I suspect your data may not be in the format you expect it to be.

How do you remove a value that has an empty key from an associative array in PHP?

I have a key that appears to be an empty string, however using unset($array[""]); does not remove the key/value pair. I don't see another function that does what I want, so I'm guessing it's more complicated that just calling a function.
The line for the element on a print_r is [] => 1, which indicates to me that the key is the empty string.
Using var_export, the element is listed as '' => 1.
Using var_dump, the element is listed as [""]=>int(1).
So far, I have tried all of the suggested methods of removal, but none have removed the element. I have tried unset($array[""]);, unset($array['']);, and unset($array[null]); with no luck.
Try unset($array[null]);
If that doesn't work, print the array via var_export or var_dump instead of print_r, since this allows you to see the type of the key. Use var_export to see the data in PHP syntax.
var_export($array);
Note that var_export does not work with recursive structures.
Tried:
$someList = Array('A' => 'Foo', 'B' => 'Bar', '' => 'Bah');
print_r($someList);
echo '<br/>';
unset($someList['A']);
print_r($someList);
echo '<br/>';
unset($someList['']);
print_r($someList);
echo '<br/>';
Got:
Array ( [A] => Foo [B] => Bar [] => Bah )
Array ( [B] => Bar [] => Bah )
Array ( [B] => Bar )
You should analyse where the key come from, too...
My guess is that it's not an empty string. Try the following to see what you get:
foreach ($array as $index => $value) {
echo $index;
echo ' is ';
echo gettype($index);
echo "\n";
}
Try using var_dump instead of print_r. This may give you a better idea of what exactly the key is.
Not sure what to tell you. Running this script
<?php
$arr = array(
false => 1
, true => 2
, null => 3
, 'test' => 4
// , '' => 5
);
print_r( $arr );
foreach ( $arr as $key => $value )
{
var_dump( $key );
}
unset( $arr[''] );
print_r( $arr );
I get the following output
Array
(
[0] => 1
[1] => 2
[] => 3
[test] => 4
)
int(0)
int(1)
string(0) ""
string(4) "test"
Array
(
[0] => 1
[1] => 2
[test] => 4
)
See how the "null" array key was type converted to an empty string?
Are you sure you are not working with a copy of the array? If you did this call to unset() from inside a function, it's possible that you are.
This was tested on PHP 5.2.0
Please post the code you use to remove the element as well your checker code before and after that line.
What I'm looking for is something like this:
var_export($array);
echo "\n";
unset($array[""]);
var_export($array);
Please also post the complete output of both var_export lines.
I'm looking for something like this:
array (
'' => 1,
)
array (
)

Categories