PHP remove array if subarray empty - php

my array image just like this, if subarray "name" is empty or null i want delete array, how to do that ?
here my current script
$data = array();
$fixedData = array();
$countyName = array();
$numrow = 2;
echo "<pre>";
// insert to tb participant => 1
foreach($sheet as $key => $row){
$data[] = array(
'name' => $this->split_name($row['B']),
'phone' => $row['D'],
'mobile' => $row['E'],
'institution' => $row['F'],
'departement' => $row['G'],
'address' => $row['H'],
'country' => $row['I'],
);
$numrow++;
}
unset($data[0]); //delete first row
$data = array_values($data);
//loop search data
var_dump ($data);
die();

Assume that you have the following data set,
$array = [
[
'name' => 'not null', 'phone' => 12546
],[
'name' => '', 'phone' => 852147
],[
'name' => null, 'phone' => 96325874
],[
'name' => 'have value', 'phone' => 12546
],
];
You can filter the nulled or empty values like several ways :
1-
foreach ($array as $key => &$value) {
if (empty($value['name']) || is_null($value['name'])) {
$value = null;
}
}
$array = array_filter($array);
2-
$newData = [];
foreach ($array as $key => $value) {
if (!empty($value['name']) && !is_null($value['name'])) {
$newData[] = $value;
}
}
3- using array_walk
$newData = [];
array_walk($array, function ($value, $key) use (&$newData) {
if (!empty($value['name']) && !is_null($value['name'])) {
$newData[] = $value;
}
});
4- using array_filter
$newData = array_filter($array, function ($value) {
if (!empty($value['name']) && !is_null($value['name'])) {
return $value;
}
});

<?php
$data = array();
$fixedData = array();
$countyName = array();
$numrow = 2;
echo "<pre>";
// insert to tb participant => 1
foreach($sheet as $key => $row){
if($this->split_name($row['B'])!=='' && $this->split_name($row['B'])!==NULL){
$data[] = array(
'name' => $this->split_name($row['B']),
'phone' => $row['D'],
'mobile' => $row['E'],
'institution' => $row['F'],
'departement' => $row['G'],
'address' => $row['H'],
'country' => $row['I'],
);
$numrow++;
}
}
//loop search data
var_dump ($data);
die();
I simple put an if condition inside your loop so you can check if your value is null or empty and if it is then you don't fill your new array. Also moved your counter inside the if so you increment it only in a success array push
A more "elegant" way for your if condition is this as well:
if (!empty($this->split_name($row['B'])) && !is_null($this->split_name($row['B'])))

Related

How to group the nested array based on id?

Basically I have an associative array from the database like below,
persons = [
[id=>1, name=>adam, hobbyId=>x, hobbyName=> swim],
[id=>2, name=>brian, hobbyId=>y, hobbyName=> read],
[id=>1, name=>adam, hobbyId=>z, hobbyName=> sing]
]
I want to convert it to a new style like JSON object, something like this,
new_persons = [
[id=>1, name=>adam, hobbies => [[hobbyId=>x, hobbyName=> swim],[hobbyId=>z,
hobbyName=> sing]],
[id=>2, name=>brian, hobbies => [[hobbyId=>y, hobbyName=>read]]
]
What I have tried is,
$new_persons = array();
if (count($persons) > 0) {
foreach ($persons as $item) {
$detail = array(
'id' => $item['id'],
'name' => $item['name'],
'hobbies' => [['hobbyId'=>$item['hobbyId'],'hobbyName'=>$item['hobbyName']]]
);
if (in_array($item['id'], $newArray)) {
array_push($newArray['hobbies'], ['hobbyId'=>$item['hobbyId'],'hobbyName'=>$item['hobbyName']]);
} else {
array_push($newArray, $detail);
}
}
}
But it doesn't meet my requirements, What is wrong with my code?
$t2 = [];
foreach ($t as $item) {
if (!isset($t2[$item['id']])) {
$t2[$item['id']] = [
'id' => $item['id'],
'name' => $item['name'],
];
}
$t2[$item['id']]['hobbies'][] = [
'hobbyId' => $item['hobbyId'],
'hobbyName' => $item['hobbyName'],
];
}

PHP create json with foreach loop

I want to prepare json with php as follows. But, the services section does not occur nested. How can I get json output as below by correcting php code?
foreach($this->input->post('name') as $key => $value){
$services = [];
foreach($this->input->post('services') as $value2){
$services[] = array(
'service_name' => $value2
);
}
$json[] = array(
'name' => $this->input->post('name')[$key],
'surname' => $this->input->post('surname')[$key],
'birthday' => $this->input->post('birthday')[$key],
'services' => $services
);
}
echo json_encode($json);
I want this:
[
{
"name":"aa",
"surname":"bb",
"birthday":"10.07.2019",
"services":[
{
"service_name":"test1",
"service_name":"test2",
},
]
},
{
"name":"cc",
"surname":"dd",
"birthday":"20.07.2019",
"services":[
{
"service_name":"test3",
"service_name":"test4",
},
]
}
]
You can try following code:
foreach($this->input->post('name') as $key => $value){
$services = [];
$count = 0;
foreach($this->input->post('services') as $value2){
$services["service".$count] = $value2;
$count++;
}
$json[] = array(
'name' => $this->input->post('name')[$key],
'surname' => $this->input->post('surname')[$key],
'birthday' => $this->input->post('birthday')[$key],
'services' => $services
);
}
$json = json_encode($json);
$json = preg_replace('/"service\d+"/', "service_name", $json);
echo $json;

PHP foreach with a condition only extract first value

I have an array as
$apps = array(
array(
'id' => '2',
'name' => 'Popcorn'
),
array(
'id' => '1',
'name' => 'EveryCord'
),
array(
'id' => '2',
'name' => 'AirShou'
),
Here I want to print names where id="2". So I tried it with following code.
foreach ( $apps as $var ) if ($var['id'] == "2") {
echo $var['name']
}
The problem is that it only print first result of the array as
"Popcorn".
But I want to extract all result which are
"Popcorn and Airshou"
How can I fix this. Can someone help me !
Try this;
$apps = [
['name' => 'Fish', 'id' => 2],
['name' => 'Chips', 'id' => 1],
['name' => 'Sticks', 'id' => 2],
];
$using = [];
foreach ( $apps as $var ) {
if ($var['id'] == "2") {
$using[] = $var['name'];
}
}
echo implode(" and ", $using);
RESULT:
You can create a sample array.
And append the name to it, if it is id=2
Code:
$apps = [
['id' => '2', 'name' => 'Popcorn'],
['id' => '1', 'name' => 'EveryCord'],
['id' => '2', 'name' => 'AirShou']
];
$names = [];
if (! empty($apps)) {
foreach ($apps as $elem) {
if ($elem['id'] == 2) {
$names[] = $elem['name'];
}
}
}
$finalName = ! empty($names) ? implode(' and ', $names) : '';
echo '<pre>';print_r($finalName);echo '</pre>';
// Output: Popcorn and AirShou
You can filter the array on the item id and then retrieve the column name:
array_column(array_filter($apps, function($v){return '2' === $v['id'];}), 'name')
result:
array(2) {
[0] =>
string(7) "Popcorn"
[1] =>
string(7) "AirShou"
}
Change your loop by this code, and you will got both names,
foreach ( $apps as $var ){
if ($var['id'] == "2") {
echo $var['name'];
}
}
Just grab names in array then implode it like this:
$temp = array();
foreach ( $apps as $var ) if ($var['id'] == "2") {
$temp[] = $var['name']
}
echo implode(' and ', $temp);

PHP - How to create such array?

The question is simple, I want to create the array below dynamically, but the code I got now only outputs the last row. Is there anybody who knows what is wrong with my dynamically array creation?
$workingArray = [];
$workingArray =
[
0 =>
[
'id' => 1,
'name' => 'Name1',
],
1 =>
[
'id' => 2,
'name' => 'Name2',
]
];
echo json_encode($workingArray);
/* My not working array */
$i = 0;
$code = $_POST['code'];
$dynamicArray = [];
foreach ($Optionsclass->get_options() as $key => $value)
{
if ($value['id'] == $code)
{
$dynamicArray =
[
$i =>
[
'id' => $key,
'name' => $value['options']
]
];
$i++;
}
}
echo json_encode($dynamicArray);
You dont need to have the $i stuff that is adding another level to your array that you dont want.
$code = $_POST['code'];
$dynamicArray = [];
foreach ($Optionsclass->get_options() as $key => $value)
{
if ($value['id'] == $code)
{
$dynamicArray[] = ['id' => $key, 'name' => $value['options'];
}
}
echo json_encode($dynamicArray);
You are creating a new dynamic array at each iteration:
$dynamicArray =
[
$i =>
[
'id' => $key,
'name' => $value['options']
]
];
Instead, declare $dynamicArray = []; above the foreach, and then use:
array_push($dynamicArray, [ 'id' => $key, 'name' => $value['options']);
inside the array.

PHP - search in array and create new one

I want to avoid if it is possible foreach combined with if. I want to search the array, take out the matches and create new one base on result.
In this example I want to create separate arrays for each os -
$os1 = $array;
$os2 = $array...
Array looks like this:
$array = [
0 => [
'id' => 1,
'name' => 'name',
'os' => 1
],
1 => [
'id' => 2,
'name' => 'name',
'os' => 1
],
2 => [
'id' => 3,
'name' => 'name',
'os' => 2
],
3 => [
'id' => 3,
'name' => 'name',
'os' => 2
]
];
Use array_filter to reduce the input array to the expected result
$os = 1;
$data = array_filter($array, function($item) use ($os) {
return $item['os'] == $os;
});
The short one
$os1 = [];
$os2 = [];
$os3 = [];
foreach ($array as $item) {
${'os' . $item['os']}[] = array('id' => $item['id'], 'name' => $item[$name];
}
The better one
$os1 = [];
$os2 = [];
$os3 = [];
foreach ($array as $item) {
switch($item['os']) {
case 1:
$os1[] = array('id' => $item['id'], 'name' => $item[$name]);
break;
case 2:
$os2[] = array('id' => $item['id'], 'name' => $item[$name]);
break;
case 3:
$os3[] = array('id' => $item['id'], 'name' => $item[$name]);
break;
default:
throw new Exception('Unknown Os');
}
}
Also you maybe want to assign array($item['id'] => $item[$name]); instead of array('id' => $item['id'], 'name' => $item[$name]);
$os1 = [];
$os2 = [];
$os3 = [];
foreach ($array as $item) {
${'os' . $item['os']}[] = array($item['id'] => $item[$name]);
}

Categories