Skip to content

Commit

Permalink
added select method
Browse files Browse the repository at this point in the history
  • Loading branch information
nahid committed Jun 11, 2018
1 parent 67bcd54 commit 9c824a2
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 15 deletions.
25 changes: 13 additions & 12 deletions examples/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,20 @@
use Nahid\JsonQ\Jsonq;


$result = '';
Jsonq::macro('less', function ($payable, $val) {
return $payable < $val;
});

Jsonq::macro('int', function ($payable, $val) {
return is_integer($payable);
});

//$result = '';
//Jsonq::macro('less', function ($payable, $val) {
// return $payable < $val;
//});
//
//Jsonq::macro('int', function ($payable, $val) {
// return is_integer($payable);
//});
//
$jq = new Jsonq('data.json');

$result = $jq->from('products')
->where('cat', 'int', 0)

->sum('price');
->select('name', 'id')
->where('cat', '=', 2)
->sortBy('user_id', 'asc')
->get();
dump($result);
29 changes: 27 additions & 2 deletions src/JsonQueriable.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ trait JsonQueriable
*/
protected $_map;

/**
* contains column names
* @var array
*/
protected $_select = [];

/**
* Stores base contents.
*
Expand Down Expand Up @@ -185,6 +191,24 @@ public function isJson($value, $isReturnMap = false)
return $isReturnMap ? $data : true;
}


/**
* selecting specific column
*
* @param $array
* @return array
*/
protected function selectColumn($array)
{
$keys = $this->_select;

if (count($keys) == 0) {
return $array;
}

return array_intersect_key($array, array_flip((array) $keys));
}

/**
* Prepare data for result
*
Expand All @@ -195,12 +219,13 @@ public function isJson($value, $isReturnMap = false)
protected function prepareResult($data, $isObject)
{
$output = [];
if (is_array($data)) {
if ($this->isMultiArray($data)) {
foreach ($data as $key => $val) {
$val = $this->selectColumn($val);
$output[$key] = $isObject ? (object) $val : $val;
}
} else {
$output = json_decode(json_encode($data), $isObject);
$output = json_decode(json_encode($this->selectColumn($data)), !$isObject);
}

return $output;
Expand Down
18 changes: 17 additions & 1 deletion src/Jsonq.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,22 @@ public function at($node = null)
return $this->from($node);
}

/**
* select desired column
*
* @param ... scalar
* @return $this
*/
public function select()
{
$args = func_get_args();
if (count($args) > 0 ){
$this->_select = $args;
}

return $this;
}

/**
* getting prepared data
*
Expand All @@ -98,7 +114,7 @@ public function get($object = true)
}

if (!$this->isMultiArray($this->_map)) {
return (object) $this->_map;
return (object) $this->selectColumn($this->_map);
}

return $this->prepareResult($this->_map, $object);
Expand Down

0 comments on commit 9c824a2

Please sign in to comment.