Remove every row where entry equal an empty string - php

I have an array with several rows containing those values (id,date,latlng,transport). I want to remove the entire row when transport = "".
I tried while, for and foreach but the problem is : when I find more than 1 entry to delete, the "$i" doesn't match anymore with the appropriate row.
for($i=0;$i<count($json_a[data][entrees]);$i++)
{
if($json_a[data][entrees][$i][transport]!="")
{
array_splice($json_a[data][entrees],$i,1);
//first removal is OK. Second won't scope the good row
}
}
I managed to make it work by creating a second array and copying the good rows inside, then replacing the first array. But there are probably better solutions, aren't they ?

there is no $i in a foreach loop.
foreach($json_a['data']['entrees'] as $entryKey => $entry){
if($entry['transport']!=""){
unset($json_a['data']['entrees'][$entryKey]);
}
}

for($i=0;$i<count($json_a[data][entrees]);$i++)
{
if($json_a[data][entrees][$i][transport]=="")
{
unset($json_a[data][entrees][$i]);
}
}
print_r($json_a[data][entrees])
Hope this helps!

Try this:
foreach( $json_a['data']['entrees'] as $key => $entry ){
if( $entry['transport'] != "" ){
array_splice($json_a['data']['entrees'], $key, 1);
}else{
unset($json_a['data']['entrees'][$key]);
}
}

You are using PHP array_splice where it reads:
Remove a portion of the array and replace it with something else
To remove one entry from an Array, you should use PHP unset where it reads:
Unset a given variable.
So, your code should be:
<?php
for($i=0;$i<count($json_a[data][entrees]);$i++)
{
if($json_a[data][entrees][$i][transport]!="")
{
//remove this entry from the array
unset($json_a[data][entrees][$i]);
}
}
?>
Test Case:
// Sample Array with 4 entries
$json_a = array(
"data" => array (
"entrees" => array(
array (
"id" => 14,
"date" => '2012-06-14',
"latlng" => '14.000000, -9.00000',
"transport" => ''
),
array(
"id" => 13,
"date" => '2012-06-14',
"latlng" => '13.000000, -8.00000',
"transport" => '12'
),
array(
"id" => 12,
"date" => '2012-06-14',
"latlng" => '12.000000, -7.00000',
"transport" => '45'
),
array(
"id" => 11,
"date" => '2012-06-14',
"latlng" => '11.000000, -6.00000',
"transport" => ''
)
)
)
);
Control Output:
var_dump($json_a);
Outputs:
array(1) { ["data"]=> array(1) { ["entrees"]=> array(4) { [0]=> array(4) { ["id"]=> int(14) ["date"]=> string(10) "2012-06-14" ["latlng"]=> string(19) "14.000000, -9.00000" ["transport"]=> string(0) "" } 1=> array(4) { ["id"]=> int(13) ["date"]=> string(10) "2012-06-14" ["latlng"]=> string(19) "13.000000, -8.00000" ["transport"]=> string(2) "12" } 2=> array(4) { ["id"]=> int(12) ["date"]=> string(10) "2012-06-14" ["latlng"]=> string(19) "12.000000, -7.00000" ["transport"]=> string(2) "45" } [3]=> array(4) { ["id"]=> int(11) ["date"]=> string(10) "2012-06-14" ["latlng"]=> string(19) "11.000000, -6.00000" ["transport"]=> string(0) "" } } } }
Run the Cycle:
for($i=0;$i<count($json_a[data][entrees]);$i++)
{
if($json_a[data][entrees][$i][transport]!="")
{
//remove this entry from the array
unset($json_a[data][entrees][$i]);
}
}
Confirmation Output:
var_dump($json_a);
Outputs:
array(1) { ["data"]=> array(1) { ["entrees"]=> array(2) { [0]=> array(4) { ["id"]=> int(14) ["date"]=> string(10) "2012-06-14" ["latlng"]=> string(19) "14.000000, -9.00000" ["transport"]=> string(0) "" } [3]=> array(4) { ["id"]=> int(11) ["date"]=> string(10) "2012-06-14" ["latlng"]=> string(19) "11.000000, -6.00000" ["transport"]=> string(0) "" } } } }

Related

How to get specific values out of all indexes in an array

I have an array which I want to iterate over to push the items into a select box, but I can't figure out how to do it.
The array I get from the function:
array(2) {
["de"]=> array(10) {
["id"]=> int(10)
["order"]=> int(1)
["slug"]=> string(2) "de"
["locale"]=> string(5) "de-DE"
["name"]=> string(7) "Deutsch"
["url"]=> string(34) "http://localhost/werk/Mol/de/haus/"
["flag"]=> string(66) "http://localhost/werk/Mol/wp-content/plugins/polylang/flags/de.png"
["current_lang"]=> bool(false)
["no_translation"]=> bool(false)
["classes"]=> array(4) {
[0]=> string(9) "lang-item"
[1]=> string(12) "lang-item-10"
[2]=> string(12) "lang-item-de"
[3]=> string(15) "lang-item-first"
}
}
["nl"]=> array(10) {
["id"]=> int(3)
["order"]=> int(2)
["slug"]=> string(2) "nl"
["locale"]=> string(5) "nl-NL"
["name"]=> string(10) "Nederlands"
["url"]=> string(26) "http://localhost/werk/Mol/"
["flag"]=> string(66) "http://localhost/werk/Mol/wp-content/plugins/polylang/flags/nl.png"
["current_lang"]=> bool(true)
["no_translation"]=> bool(false)
["classes"]=> array(4) {
[0]=> string(9) "lang-item"
[1]=> string(11) "lang-item-3"
[2]=> string(12) "lang-item-nl"
[3]=> string(12) "current-lang"
}
}
}
I tried a foreach but I did only get the indexes of the array
<?php
$translations = pll_the_languages(array('raw' => 1));
$lang_codes = array();
foreach ($translations as $key => $value) {
array_push($lang_codes, $key);
}
?>
I need the language slug, URL, and flag from all indexes in this array (de & nl), what should I do?
A simple iteration over the outer array and then pick the values you want from the sub array.
<?php
$translations = pll_the_languages(array('raw' => 1));
$lang_codes = array();
foreach ($translations as $lang => $info) {
$lang_codes[$lang] = [ 'slug' => $info['slug'],
'url' => $info['url'],
'flag' => $info['flag']
];
}
?>
You can approach this as
$res = [];
foreach($translations as $key => $value){
$res[$key] = [
'slug' => $value['slug'],
'url' => $value['url'],
'flag' => $value['flag']
];
}
Live Demo

How to remove items that exist in the array from object?

This is how my array looks like:
array(3) {
[0]=>
string(3) "600"
[1]=>
string(3) "601"
[2]=>
string(3) "603"
}
This is how my object looks like:
array(7) {
[0]=>
object(stdClass)#688 (6) {
["id"]=>
string(3) "601"
["name"]=>
string(10) "test8opkpo"
["avatar"]=>
string(85) "http://avatars/user/medium.png"
["url"]=>
string(86) "/index.php"
["isOnline"]=>
int(0)
["lastseen"]=>
string(11) "2 weeks ago"
}
[1]=>
object(stdClass)#689 (6) {
["id"]=>
string(3) "604"
["name"]=>
string(6) "nopita"
["avatar"]=>
string(85) "http://avatars/user/medium.png"
["url"]=>
string(82) "/index.php"
["isOnline"]=>
int(0)
["lastseen"]=>
string(10) "1 week ago"
}
[2]=>
object(stdClass)#690 (6) {
["id"]=>
string(3) "603"
["name"]=>
string(6) "test_b"
["avatar"]=>
string(85) "http://avatars/user/medium.png"
["url"]=>
string(82) "/index.php"
["isOnline"]=>
int(0)
["lastseen"]=>
string(11) "6 hours ago"
}
Now I want to remove from the object, each item's id that matches the value inside the array.
So final output of the object should not contain id's that present in the array given. How to do that?
I tried using array_diff_key and unset to no avail.
$contactArray[$i] represent each id in the object
if (in_array($contactArray[$i], $array)) {
$a = array_diff_key($results->contacts, [$i => $contactArray[$i]]);
}
I created my own set of examples to simulate what you want to happen on your array:
$x = array('600','601', '603');
$y = array(
array("id" => "600",
"name" => "test",
"avatar" => "image"
),
array("id" => "601",
"name" => "test1",
"avatar" => "image1"
),
array("id" => "602",
"name" => "test2",
"avatar" => "image2"
),
array("id" => "603",
"name" => "test3",
"avatar" => "image3"
),
array("id" => "604",
"name" => "test4",
"avatar" => "image4"
)
);
echo '<pre>';
var_dump($y);
echo '</pre>';
$new_arr_ = array();
for($i = 0, $ctr = count($y); $i < $ctr; $i++) {
if(!in_array($y[$i]["id"], $x)) {
$new_arr_[] = array($y[$i]["id"], $y[$i]["name"], $y[$i]["avatar"]);
}
}
echo '<pre>';
var_dump($new_arr_);
echo '</pre>';
Hope it helps.
If I understand you correctly the following should work:
$contactArray = array_filter($contactArray, function ($v) use ($array) {
return !in_array(isset($v->id)?$v->id:null, $array);
});

Create a checkbox for tags in Wordpress

Im editing a plugin because I want to create a checkbox for the tags the plugin has. In this moment Ive got in a variable, this array:
array(9) { [129]=> object(EM_Tag)#84 (15) { ["id"]=> string(3) "129" ["term_id"]=> string(3) "129" ["name"]=> string(35) "Accessible for non-English speakers" ["slug"]=> string(11) "non-english" ["term_group"]=> string(1) "0" ["term_taxonomy_id"]=> string(3) "129" ["taxonomy"]=> string(10) "event-tags" ["description"]=> string(0) "" ["parent"]=> string(1) "0" ["count"]=> string(1) "0" ["fields"]=> array(0) { } ["required_fields"]=> array(0) { } ["feedback_message"]=> string(0) "" ["errors"]=> array(0) { } ["mime_types"]=> array(3) { [1]=> string(3) "gif" [2]=> string(3) "jpg" [3]=> string(3) "png" } } }
There are more tags but I just put one. I would like to generate a checkbox for each tag.
One solution is to iterate over the array that you provided and access the fields that way. I made a shortened array with proper indentation based on your example provided. It seems to be the same but let me know otherwise.
$array = array(
129 => array(
'id' => '129',
'name' => 'Accessible for non-English Speakers'
),
130 => array(
'id' => '130',
'name' => 'A second piece of information'
),
131 => array(
'id' => '131',
'name' => 'A third piece of information'
)
);
// Iterate over the array
foreach ($array as $c) {
// Access the required data
$id = $c['id'];
$name = $c['name'];
// Generate your checkbox
print "<input type='checkbox' name='$name' id='$id'>";
}

How to filter array to get only the object and not array in PHP

I'm not even sure what to search for for this question. What I really want is I have an array of objects like this
array(3) {
[0]=>
object(stdClass)#423 (4) {
["name"]=>
string(3) "Blah"
["full_name"]=>
string(10) "/Blah"
["id"]=>
string(32) "BlahBlah"
["parent_id"]=>
string(32) "BlahBlah"
}
[1]=>
object(stdClass)#422 (4) {
["name"]=>
string(8) "Blah1"
["full_name"]=>
string(9) "Blah2"
["id"]=>
string(32) "BlahBlah2"
["parent_id"]=>
NULL
}
[2]=>
object(stdClass)#421 (4) {
["name"]=>
string(4) "Blah3"
["full_name"]=>
string(11) "Blah3"
["id"]=>
string(32) "BlahBlah3"
["parent_id"]=>
string(32) "BlahBlahBlah3"
}
}
I want to filter to just the object that I want so what I did was
$found_label = array_filter($labels, function($obj) use($label) {
return $obj->name === $label;
});
But then the results I got is this
array(1) {
[1]=>
object(stdClass)#422 (4) {
["name"]=>
string(8) "Blah1"
["full_name"]=>
string(9) "Blah1"
["id"]=>
string(32) "BlahBlah2"
["parent_id"]=>
NULL
}
}
But what I really want is just this
object(stdClass)#422 (4) {
["name"]=>
string(8) "Blah1"
["full_name"]=>
string(9) "Blah1"
["id"]=>
string(32) "BlahBlah2"
["parent_id"]=>
NULL
}
Then I have to do this to just get the actual object
$theKey = key($found_label);
return $found_label[$theKey];
I thought they should be a better way of doing this, also I'm new to PHP.
You can't do that with array_filter, there is no way to stop it and return only the first result. If you can't use the key to extract the result you want from the array returned from array_filter, you should use a loop. Something like this:
$label = "wantedLabel";
foreach ($labels as $l) {
if( $l->name === $label ) {
print_r ($l);
break;
}
}
This:
<?php
$labels = array(
"0" => (object) array('name' => "name1", "title" => "title1"),
"1" => (object) array('name' => "name2", "title" => "title2")
);
$label = "name1";
$found_label = array_filter($labels, function($obj) use($label) {
return $obj->name === $label;
});
print_r($found_label[0]);
Produces:
stdClass Object ( [name] => name1 [title] => title1 )

PHP: Change array1 value based on array2 value

I have 2 arrays. Sometimes a key/value from array1 may equals to key/value of array2. If that is true, change 'status' from the specific key/value from array2, to a new value. Does that make sense?
Here is where I am at:
foreach($array1 as $i=>$x){
foreach($array2 as $k=>$y){
if($x['url'] == $y['url']){
// Up to here works
foreach($i as &$value) {
$value['status'] = 'new value';
}
break;
}
}
}
This are my arrays:
array(1) {
[0]=> array(1) {
["url"]=> string(104) "aHR0cDovL3lvdXR1YmUuY29t"
["date"]=> string(19) "2014-01-06 21:44:39"
["status"]=> string(1) "0"
}
[1]=> array(1) {
["url"]=> string(28) "d3d3LnR3aXR0ZXIuY29t"
["date"]=> string(19) "2014-01-06 14:28:32"
["status"]=> string(1) "0"
}
}
and array2:
array(2) {
[0]=> array(2) {
["url"]=> string(104) "aHR0cDovL3lvdXR1YmUuY29t"
["date"]=> string(19) "2014-01-06 21:44:39"
}
[1]=> array(2) {
["url"]=> string(28) "aHR0cDovL3d3dy5nb29nbGUuY29t"
["date"]=> string(19) "2014-01-06 14:28:32"
}
}
Up to the comment it works. From there after, how can I change that specific key/value to a new value? My current example changes all key 'status' to 'new value'.
You don't have to loop again through array1 just change the key of it
$array1[$i]['status'] = 'new value';
How about this:
<?php
$array1 = array(
array(
"url" => "aHR0cDovL3lvdXR1YmUuY29t",
"date" => "2014-01-06 21:44:39",
"status" => "0"
)
);
$array2 = array(
array(
"url" => "aHR0cDovL3lvdXR1YmUuY29t",
"date" => "2014-01-06 21:44:39",
)
);
array_walk($array2, function($arr2) use (&$array1)
{
foreach($array1 as &$arr1)
{
if($arr2['url'] == $arr1['url'])
$arr1['status'] = "something";
}
});
print_r($array1);
Output:
Array
(
[0] => Array
(
[url] => aHR0cDovL3lvdXR1YmUuY29t
[date] => 2014-01-06 21:44:39
[status] => something
)
)

Categories