php flattening nested array - php

I have an array like this
$array:
{ name : xyz
version : Array[2]
{
0 : Array[2]
{
id : 1
batch : 1
}
1 : Array[2]
{
id : 2
batch : 2
}
}
}
How can I create an array like this:
$results[] =
name:xyz, version:0, id:1, batch:1
name:xyz, version:1, id:2, batch:2
I want an array where the common fields are repeated.

Do you mean:
$results = array();
$results[] = array('name' => 'xyz', 'version' => 0, 'id' => 1, 'batch' => 1);
$results[] = array('name' => 'xyz', 'version' => 1, 'id' => 1, 'batch' => 1);
Then access the first row by $results[0]['name']
Or second row by $results[1]['name']
EDIT
To convert from $array to $results, I have to assume your $array looks like this.
$array =
array('name' => 'xyz',
'version' => array(
0 => array(
'id' => 1,
'batch' => 1
),
1 => array(
'id' => 2,
'batch' => 2
)
)
);
then
$results = array();
$name = $array['name'];
foreach($array['version'] as $version => $idandbatch)
{
$results[] = array('name' => $name,
'version' => $version,
'id' => $idandbatch['id'],
'batch' => $idandbatch['batch']);
}
You can access the array
foreach($results as $values)
{
echo $values['name'];
echo $values['version'];
echo $values['id'];
echo $values['batch'];
}

Related

How to check JSON String based on another JSON String?

I'd like to do a loop with these JSON strings.
$json_m = '[
{"name":"1","value":"1"},
{"name":"2","value":"2"},
{"name":"3","value":"3"},
{"name":"4","value":"4"},
{"name":"5","value":"5"},
]';
$json_a = '[
{"name":"1-m","value":"1"},
{"name":"2-m","value":"3"},
{"name":"3-m","value":"5"},
]';
I do a loop and on $json_m. If the value exists in both JSON, I set the parameter to TRUE
This is my current code:
$jm = json_decode($json_m, true);
$ja = json_decode($json_a, true);
$i = 0;
$is_exist = FALSE;
foreach($jm as $rows ){
if($rows["value"] == $ja[$i]["value"]){
$is_exist = TRUE;
}
$dataadd = array ( 'ID' => $i,
'NAME' => $rows["value"],
'STATUS' => $is_exist
);
$i++;
}
This script returns as all FALSE, based on my example the STATUS should return like this:
TRUE
FALSE
TRUE
FALSE
TRUE
Do I miss something or what? Any help is greatly appreciated.
You can do using array_search like below
$json_m = '[
{"name":"1","value":"1"},
{"name":"2","value":"2"},
{"name":"3","value":"3"},
{"name":"4","value":"4"},
{"name":"5","value":"5"}
]';
$json_a = '[
{"name":"1-m","value":"1"},
{"name":"2-m","value":"3"},
{"name":"2-m","value":"3"},
{"name":"3-m","value":"5"}
]';
$jm = json_decode($json_m, true);
$ja = json_decode($json_a, true);
$javal = array_unique(array_column($ja, 'value'));
$is_exist = FALSE;
$dataadd =[];
foreach($jm as $i=> $rows ){
$is_exist = FALSE;
if(is_numeric(array_search($rows["value"], $javal))) {
$is_exist = TRUE;
}
$dataadd[] = array ( 'ID' => $i,
'NAME' => $rows["value"],
'STATUS' => $is_exist
);
}
print_r($dataadd);
You could make your life easier by extracting all the value values from $ja using array_column; you can then search that using in_array. You can then iterate $jm using array_map to produce an array of $dataadd values:
$ja_values = array_column($ja, 'value');
$dataadd = array_map(fn ($arr, $idx) => array('ID' => $idx, 'NAME' => $arr['value'], 'STATUS' => in_array($arr['value'], $ja_values)), $jm, array_keys($jm));
var_export($dataadd);
Output (for your sample data):
array (
0 =>
array (
'ID' => 0,
'NAME' => '1',
'STATUS' => true,
),
1 =>
array (
'ID' => 1,
'NAME' => '2',
'STATUS' => false,
),
2 =>
array (
'ID' => 2,
'NAME' => '3',
'STATUS' => true,
),
3 =>
array (
'ID' => 3,
'NAME' => '4',
'STATUS' => false,
),
4 =>
array (
'ID' => 4,
'NAME' => '5',
'STATUS' => true,
),
)

How can I update the key start from one on the php?

My first array like this :
$photoList = array(
array(
'id' => 1,
'name' => 'chelsea.jpg'
),
array(
'id' => 2,
'name' => 'mu.jpg'
),
array(
'id' => 3,
'name' => 'city.jpg'
)
);
My second array like this :
photo = array('cover1'=>'liverpool.jpg', 'cover2'=>'city.jpg');
My code like this :
$photo = array_filter($photo, function($item) use ($photoList) {
return in_array($item, array_column($photoList, 'name')) ;
});
if (empty($photo))
$photo=null;
If I run : echo '<pre>';print_r($photo);echo '</pre>';, the result like this :
Array
(
[cover2] => city.jpg
)
I want the result like this :
Array
(
[cover1] => city.jpg
)
So if there is no cover1, the cover2 changed to be cover1
How can I do it?
You could re-index the keys like this :
$photoList = array(
array(
'id' => 1,
'name' => 'chelsea.jpg'
),
array(
'id' => 2,
'name' => 'mu.jpg'
),
array(
'id' => 3,
'name' => 'city.jpg'
)
);
$photo = array('cover1'=>'liverpool.jpg', 'cover2'=>'city.jpg');
$photo = array_filter($photo, function($item) use ($photoList) {
return in_array($item, array_column($photoList, 'name')) ;
});
if (empty($photo)){
$photo = null;
} else {
$idx = 1 ;
foreach ($photo as $key => $value) {
unset($photo[$key]);
$photo['cover'.$idx++] = $value;
}
}
print_r($photo);
Outputs :
Array
(
[cover1] => city.jpg
)
I'm not sure about what you really need. Assuming you want to do that recursively, I hope this helps:
$label = 'cover';
$index = 1;
$a_keys = array_keys($photo);
$new_photo = [];
foreach($a_keys AS $k=>$v){
$new_photo[$label.$index] = $photo[$k];
$index++;
}
$photo = $new_photo;
It will rewrite your array with wanted naming style.

how to check whether 4 exist or not in array at 'id' key position

how to check whether 4 exist or not in array at id key position
$arr = array(
array(
'id' => 1,
'other_data' => 'ganesh'
),
array(
'id' => 2,
'other_data' => 'ramesh'
),
array(
'id' => 3,
'other_data' => '4'
),
)
The array you provided is not a valid multi-dimensional array. You need to add commas after each array in the array. Below i use array_column and in_array without using foreach
<?php
$arr = array(
array(
'id' => 1,
'other_data' => 'ganesh'
),//add comma
array(
'id' => 2,
'other_data' => 'ramesh'
),
array(
'id' => 3,
'other_data' => '4'
),
);
$filtered = array_column($arr, 'id');//return the id column in this array
if(in_array(4, $filtered)){//check if 4 exists
echo '4 exists';
} else {
echo '4 does not exist';
}
?>
Quite simple, loop through the array and check if the value exists:
$value = 4;
$exists = false;
foreach($arr as $innerArr){
if($innerArr['id'] == $value){
$exists = true;
break;
}
}
If $exists is now true, the value exists within the array.
Try this one, and let me know if you face any problem.
<?php
$arr = array(
array(
'id' => 1,
'other_data' => 'ganesh'
),
array(
'id' => 2,
'other_data' => 'ramesh'
),
array(
'id' => 3,
'other_data' => '4'
)
);
foreach ($arr as $key => $value) {
if (in_array("4", $value))
{
$sub_index = $value['id'];
echo "Match found at $sub_index";
break;
}
}
Just gotta loop through your array and check existence through in_array() function.
you need something like this
$arr = array(
array(
'id' => 1,
'other_data' => 'ganesh'
),
array(
'id' => 2,
'other_data' => 'ramesh'
),
array(
'id' => 3,
'other_data' => '4'
)
);
$exists_flag = false;
foreach($arr as $inside_arr)
{
if($inside_arr['other_data'] == 4) {
$exists_flag = true;
break;
}
}
print($exists_flag);
Hope this helps!
As it stand, your array is wrong, you need to separate multi array with commas, you need to not that in_array() will not work with multi array, however you may create a recursive function that will check a provided key does exists or not in an array try code below, hope it helps ,
<?php
$arr = array(
array(
'id' => 1,
'other_data' => 'ganesh'
),
array(
'id' => 2,
'other_data' => 'ramesh'
),
array(
'id' => 3,
'other_data' => '4'
)
);
function search_items($search_value, $array)
{
foreach ($array as $item) {
if (($item == $search_value) || (is_array($item) && search_items($search_value, $item))) {
return true;
}
}
return false;
}
echo search_items("4", $arr) ? 'item found' : 'item not found';
?>
$result = array_search(4, array_column($arr, 'id'));
If we split this into steps then it would be the following:
$allColumnsNamedId = array_column($arr, 'id'); // find all columns with key 'id'
$resultBoolean = array_search(4, $allColumnsNamedId); //search the array for value 4
if($resultBoolean) {
echo 'Exists';
} else {
echo 'Does not exist';
}

how to find a element in a nested array and get its sub array index

when searching an element in a nested array, could i get back it's 1st level nesting index.
<?php
static $cnt = 0;
$name = 'victor';
$coll = array(
'dep1' => array(
'fy' => array('john', 'johnny', 'victor'),
'sy' => array('david', 'arthur'),
'ty' => array('sam', 'joe', 'victor')
),
'dep2' => array(
'fy' => array('natalie', 'linda', 'molly'),
'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
'ty' => array('sharon', 'julia', 'maddy')
)
);
function recursive_search(&$v, $k, $search_query){
global $cnt;
if($v == $search_query){
/* i want the sub array index to be returned */
}
}
?>
i.e to say, if i'am searching 'victor', i would like to have 'dep1' as the return value.
Could anyone help ??
Try:
$name = 'victor';
$coll = array(
'dep1' => array(
'fy' => array('john', 'johnny', 'victor'),
'sy' => array('david', 'arthur'),
'ty' => array('sam', 'joe', 'victor')
),
'dep2' => array(
'fy' => array('natalie', 'linda', 'molly'),
'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
'ty' => array('sharon', 'julia', 'maddy')
)
);
$iter = new RecursiveIteratorIterator(new RecursiveArrayIterator($coll), RecursiveIteratorIterator::SELF_FIRST);
/* These will be used to keep a record of the
current parent element it's accessing the childs of */
$parent_index = 0;
$parent = '';
$parent_keys = array_keys($coll); //getting the first level keys like dep1,dep2
$size = sizeof($parent_keys);
$flag=0; //to check if value has been found
foreach ($iter as $k=>$val) {
//if dep1 matches, record it until it shifts to dep2
if($k === $parent_keys[$parent_index]){
$parent = $k;
//making sure the counter is not incremented
//more than the number of elements present
($parent_index<$size-1)?$parent_index++:'';
}
if ($val == $name) {
//if the value is found, set flag and break the loop
$flag = 1;
break;
}
}
($flag==0)?$parent='':''; //this means the search string could not be found
echo 'Key = '.$parent;
Demo
This works , but I don't know if you are ok with this...
<?php
$name = 'linda';
$col1=array ( 'dep1' => array ( 'fy' => array ( 0 => 'john', 1 => 'johnny', 2 => 'victor', ), 'sy' => array ( 0 => 'david', 1 => 'arthur', ), 'ty' => array ( 0 => 'sam', 1 => 'joe', 2 => 'victor', ), ), 'dep2' => array ( 'fy' => array ( 0 => 'natalie', 1 => 'linda', 2 => 'molly', ), 'sy' => array ( 0 => 'katie', 1 => 'helen', 2 => 'sam', 3 => 'ravi', 4 => 'vipul', ), 'ty' => array ( 0 => 'sharon', 1 => 'julia', 2 => 'maddy', ), ), );
foreach($col2 as $k=>$arr)
{
foreach($arr as $k1=>$arr2)
{
if(in_array($name,$arr2))
{
echo $k;
break;
}
}
}
OUTPUT :
dept2
Demo

How retrieve specific duplicate array values with PHP

$array = array(
array(
'id' => 1,
'name' => 'John Doe',
'upline' => 0
),
array(
'id' => 2,
'name' => 'Jerry Maxwell',
'upline' => 1
),
array(
'id' => 3,
'name' => 'Roseann Solano',
'upline' => 1
),
array(
'id' => 4,
'name' => 'Joshua Doe',
'upline' => 1
),
array(
'id' => 5,
'name' => 'Ford Maxwell',
'upline' => 1
),
array(
'id' => 6,
'name' => 'Ryan Solano',
'upline' => 1
),
array(
'id' =>7,
'name' => 'John Mayer',
'upline' => 3
),
);
I want to make a function like:
function get_downline($userid,$users_array){
}
Then i want to return an array of all the user's upline key with the value as $userid. I hope anyone can help. Please please...
You could do it with a simple loop, but let's use this opportunity to demonstrate PHP 5.3 anonymous functions:
function get_downline($id, array $array) {
return array_filter($array, function ($i) use ($id) { return $i['upline'] == $id; });
}
BTW, I have no idea if this is what you want, since your question isn't very clear.
If you need do search thru yours array by $id:
foreach($array as $value)
{
$user_id = $value["id"];
$userName = $value["name"];
$some_key++;
$users_array[$user_id] = array("name" => $userName, "upline" => '1');
}
function get_downline($user_id, $users_array){
foreach($users_array as $key => $value)
{
if($key == $user_id)
{
echo $value["name"];
...do something else.....
}
}
}
or to search by 'upline':
function get_downline($search_upline, $users_array){
foreach($users_array as $key => $value)
{
$user_upline = $value["upline"];
if($user_upline == $search_upline)
{
echo $value["name"];
...do something else.....
}
}
}
Code :
function get_downline($userid,$users_array)
{
$result = array();
foreach ($users_array as $user)
{
if ($user['id']==$userid)
$result[] = $user['upline'];
}
return result;
}
?>
Example Usage :
get_downline(4,$array);

Categories